go 实现HTTP 接口

go 实现HTTP 接口

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // 访问的URL
    url := "http://localhost:9333/dir/assign"
    result := reqest("POST", url)
    // 上传文件
    url = fmt.Sprintf("http://%s/%s", result["publicUrl"], result["fid"])
    result = reqest("POST", url)

    fmt.Println("------", result)
}

func reqest(method, url string) map[string]interface{} {
    // 生成client参数为默认
    client := &http.Client{}

    // 提交请求
    reqest, err := http.NewRequest(method, url, nil)
    reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
    reqest.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
    reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
    reqest.Header.Set("Cache-Control", "max-age=0")
    reqest.Header.Set("Connection", "keep-alive")
    //reqest.Header.Set("Content-Type", "multipart/form-data")
    reqest.Header.Set("Content-Type", "text/html")
    // 错误处理
    if err != nil {
        fmt.Println("请求错误", err)
    }
    // 处理返回的结果
    response, _ := client.Do(reqest)
    // 获取body 内容
    body, _ := ioutil.ReadAll(response.Body)
    // 存储返回结果
    result := make(map[string]interface{}, 0)
    // 把json转换为map
    err = json.Unmarshal(body, &result)
    if err != nil {
        fmt.Println("json 转换错误", err)
    }

    //返回的状态码
    status := response.StatusCode

    if status != 200 {
        fmt.Println("请求错误地址  错误编码:", status)
    }

    //defer reqest.Body.Close()

    return result
}

你可能感兴趣的:(go)