Categorygithub.com/pjsoftware/go-api
repositorypackage
0.4.21
Repository: https://github.com/pjsoftware/go-api.git
Documentation: pkg.go.dev

# Packages

No description provided by the author

# README

= go-api Peter Jones [email protected] :version: v0.4.15

== Go API Module ({version})

A general library for interfacing with APIs. The basic procedure is:

  • Call goapi.New() to create a new api object. This can be stored for future use.
  • Create a new ep endpoint with api.NewEndpoint(). Again, these endpoints can be stored and reused.
  • Create a single-use req request object: ep.NewRequest()
  • Modify with req.AddQuery(), req.AddHeader(), etc as required. ** AddQuery, AddHeader, etc can be chained: ep.NewRequest().AddHeader()
  • Call req.GET() or req.POST() as needed. By default, the request is discarded once used.
  • All processing of the returned data is done by the client application. go-api makes no attempt to interpret what it receives; it simply passes it back in a goapi.Result struct.

=== Simple Usage: No Auth

[,go]

api := goapi.New(apiURL) ep := api.NewEndpoint(endpointURL) req := ep.NewRequest().AddQuery(qryName,qryValue) r := req.GET()

A simple example of this from the "Chuck Norris" API (see https://github.com/PJSoftware/go-api-chuck[go-api-chuck]) is as follows:

[,go]

chuck := goapi.New("http://api.chucknorris.io/jokes") ep := chuck.NewEndpoint("/random") req := ep.NewRequest() req.AddQuery("category", "food") r := req.GET()

After receiving the results, recommended processing may look like this:

[,go]

r := req.GET() data := &MyDataStruct{} json.Unmarshal(r.Body, data)

=== Error Handling

To detect errors, can use either of these two approaches:

This library takes the approach that for any HTTP Status code other than 200 ("Success") it will return a QueryError, a custom error type. For status codes in the 200-299 range, the error name is Success (per the first example below.) For other codes, the error will be as follows:

[,go]

case code <= 99: err = ErrUnsupportedRange case code <= 199: err = ErrInformation case code <= 299: err = Success case code <= 399: err = ErrRedirection case code <= 499: err = ErrClient case code <= 599: err = ErrServer default: err = ErrUnsupportedRange

The reason for returning all non-200 results as errors is to force the client code to handle them.

==== Examples of Error Detection

[,go]

// Check for error type if errors.Is(err, goapi.Success) { fmt.Printf("Success!"); }

or

[,go]

// Do something with QueryError object var qErr *goapi.QueryError if errors.As(err, &qErr) { fmt.Printf("Error status := %d", qErr.Status()) }

QueryError has the following methods:

  • Unwrap() returns the underlying error
  • Status() returns the http status code
  • Response() returns the original HTTP response.