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. Foo string `json:"foo"`
  4. Bar string `json:"bar"`
  5. Header string `header:"X-Header"`
  6. }
  7. var domain = flag.String("domain", "http://localhost:3333", "the domain to request")
  8. func main() {
  9. flag.Parse()
  10. req := types.Request{
  11. Node: "foo",
  12. Header: "foo-header",
  13. Foo: "foo",
  14. Bar: "bar",
  15. }
  16. resp, err := httpc.Do(context.Background(), http.MethodPost, *domain+"/nodes/:node", req)
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. io.Copy(os.Stdout, resp.Body)
  22. }

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