Go Http Request

2020/07/12 Go 知识点

传输json

通过GET、POST或PUT或PATCH向服务端发送JSON

func GetJson(reqUrl string, params map[string]string, header map[string]string) (response HttpResponse) {
	response = HttpResponse{
		Url:           reqUrl,
		RequestHeader: header,
	}
	var err error
	defer func() {
		response.Error = err
	}()

	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(params)
	req, err := http.NewRequest("GET", reqUrl, b)
	if err != nil {
		return response
	}
	for k, v := range header {
		req.Header.Add(k, v)
	}

	resp, err := HttpClient.Do(req)
	if err != nil {
		return response
	}
	defer resp.Body.Close()
	p, _ := json.Marshal(params)
	response.ResponseHeader = resp.Header
	response.StatusCode = resp.StatusCode
	response.Body, err = ioutil.ReadAll(resp.Body)
	return response
}

Search

    Table of Contents