jsonclient

package module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2023 License: MIT Imports: 9 Imported by: 1

README

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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrHTTP = errors.New("http error")

ErrHTTP define an http error

Functions

This section is empty.

Types

type Client

type Client struct {
	BaseURL        *url.URL
	DefaultHeaders Headers
	Host           string
	// contains filtered or unexported fields
}

Client basic structure

func New

func New(opts Options) (*Client, error)

New function create a client using passed options BaseURL must be an HTTP or HTTPs absolute url and have a trailing slash

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

Do function executes http request using the passed request. This function automatically handles response in json to be decoded and saved into the `v` param.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest function is same of NewRequestWithContext, without context

func (*Client) NewRequestWithContext

func (c *Client) NewRequestWithContext(ctx context.Context, method string, urlStr string, body interface{}) (*http.Request, error)

NewRequestWithContext function works like the function of `net/http` package, simplified to a easier use with json request. Context and method are handled in the same way of core `net/http` package. Main differences are: * `urlString` params accept a string, that is converted to a type `url.URL` adding the client BaseURL (if provided in client options). To works correctly, urlString should not starts with `/` (otherwise BaseURL is not set) * body params in converted to a `json` buffer. If body is passed, the header `Content-Type: application/json` is automatically added to the request.

To the request are added all the DefaultHeaders (if body is passed, `application/json` content-type takes precedence over DefaultHeaders).

type HTTPError

type HTTPError struct {
	Response   *http.Response
	StatusCode int
	Err        error
	Raw        []byte
}

HTTPError struct define http response with status code not 2xx

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) Unmarshal added in v1.3.0

func (e *HTTPError) Unmarshal(v interface{}) error

Unmarshal HTTPError raw content

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

type Headers

type Headers map[string]string

Headers map. A key/value map of headers

type Options

type Options struct {
	BaseURL    string
	Headers    Headers
	HTTPClient *http.Client
	Host       string
}

Options to pass to create a new client

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL