Client

概述

HTTP Client 是一个用于发送 HTTP 请求的库,它支持如下功能:

  1. Content-Type 自动识别,仅支持 application/jsonapplication/x-www-form-urlencoded 两种格式
  2. 支持将 path 参数自动填充到 url
  3. 支持将结构体中 header 填充到 http 请求头

请求示例

GET、POST Form 请求

Get 和 Post form 请求的使用方式是一样的,只需要将结构体中的字段标记为 form 即可。

  1. type Request struct {
  2. Node string `path:"node"`
  3. ID int `form:"id"`
  4. Header string `header:"X-Header"`
  5. }
  6. var domain = flag.String("domain", "http://localhost:3333", "the domain to request")
  7. func main() {
  8. flag.Parse()
  9. req := types.Request{
  10. Node: "foo",
  11. ID: 1024,
  12. Header: "foo-header",
  13. }
  14. resp, err := httpc.Do(context.Background(), http.MethodGet, *domain+"/nodes/:node", req)
  15. // resp, err := httpc.Do(context.Background(), http.MethodPost, *domain+"/nodes/:node", req)
  16. if err != nil {
  17. fmt.Println(err)
  18. return
  19. }
  20. io.Copy(os.Stdout, resp.Body)
  21. }

以上内等同于如下 curl:

  1. # get
  2. curl --location 'http://localhost:3333/nodes/foo?id=1024' \
  3. --header 'X-Header: foo-header'
  4. # post
  5. curl --location 'http://localhost:3333/nodes/foo' \
  6. --header 'X-Header: foo-header' \
  7. --header 'Content-Type: application/x-www-form-urlencoded' \
  8. --data-urlencode 'id=1024'

POST Json 请求

Post Json 请求的使用方式是一样的,只需要将结构体中的字段标记为 json 即可。

  1. type Request struct {
  2. Node string `path:"node"`
  3. Body map[string]string `json:"body"` // json 请求体,这里以 string 为例,你可以使用任意类型
  4. Header string `header:"X-Header"`
  5. }
  6. var domain = flag.String("domain", "http://localhost:3333", "the domain to request")
  7. func main() {
  8. flag.Parse()
  9. req := types.Request{
  10. Node: "foo",
  11. Header: "foo-header",
  12. Body: map[string]string{
  13. "foo":"foo",
  14. "bar":"bar",
  15. },
  16. }
  17. resp, err := httpc.Do(context.Background(), http.MethodPost, *domain+"/nodes/:node", req)
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. io.Copy(os.Stdout, resp.Body)
  23. }

以上请求等同于如下 curl:

  1. curl --location 'http://localhost:3333/nodes/foo' \
  2. --header 'X-Header: foo-header' \
  3. --header 'Content-Type: application/json' \
  4. --data '{
  5. "foo":"foo",
  6. "bar":"bar"
  7. }'
Client - 图1温馨提示

httpc 默认使用的是 http.DefaultClient,这个不能指定