Client

Overview

HTTP Client is a library to send HTTP requests, which supports the following functions:

  1. Content-Type auto-recognition, only supported application/json and application/x-www-form-urlencoded
  2. Support auto fill path arguments to url
  3. Support to fill header in structure to the HTML request header

Request Example

GET, POST Form Requests

Get and Post form requests are used in the same way. Only fields in the structure need to be marked as 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. }

The above is equivalent to the following 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 request

Post Json requests are used in the same way. Just label the fields in the structure as 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. }

The above request is equivalent to the following 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 - 图1hint

httpc is used by http.DefaultClient, this cannot be specified