Skip to content

davidebianchi/go-jsonclient

Repository files navigation

Go Json Client

Build Status Go Report Card GoDoc Coverage Status

Go Json Client simplify the http request in json.

It uses net/http core package as http client.

Install

This library require golang at version >= 1.13

go get -u github.com/davidebianchi/go-jsonclient

Example usage

Make a request

If you want to create a json client to call a specific BaseUrl with default authentication headers:

func handleRequest () {
  opts := jsonclient.Options{
    BaseURL: "http://base-url:8080/api/url/",
    Headers: jsonclient.Headers{
      "some":  "header",
      "other": "value",
    },
  }
  client, err := jsonclient.New(opts)
  if err != nil {
    panic("Error creating client")
  }

  var data = map[string]interface{}{
    "some": "json format",
    "foo":  "bar",
    "that": float64(3),
  }
  req, err := client.NewRequest(http.MethodPost, "my/path", data)
  if err != nil {
    panic("Error creating request")
  }

  type Response struct {
    my string
  }
  v := Response{}
  // server response is: {"my": "data"}
  response, err := client.Do(req, &v)
  if err != nil {
    panic("Error making request")
  }

  if Response.my != "data" {
    panic("response data is not mine")
  }
}

The library also check the status code of the request. If status code si not 2xx, it will return an HTTPError.

API

Accepted client options

In the New function, it is possible to add some options. None of the following options are required.

  • BaseURL: set the base url. BaseURL must be absolute and starts with http or https scheme. It must end with a trailing slash /. Example of valid BaseUrl: "http://base-url:8080/api/url/"
  • Headers: a map of headers to add to all the requests. For example, it could be useful when it is required an auth header.
  • HTTPClient (default to http.DefaultClient): an http client to use instead of the default http client. It could be useful for example for testing purpose.
  • Host: set the host in all client requests.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

About

Http client to handle json request and response written in go

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages