giant

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2024 License: Unlicense Imports: 14 Imported by: 0

README

Giant

JSON API client for Golang

giant-bw

Why?

Why not just use the stdlib client?

  • set client timeouts
  • set headers
  • close body
  • reuse marshal/unmarshal logics

And from a few optional RoundTrippers:

  • log request/response (big'n!)
    • redact selected headers
    • optionally skip body
  • interpret non-200's statuses as error (see caveat)
  • basic auth

Usage

I often like to implement a service layer:

type Client interface {
  SendObject(ctx context.Context, method, path string, snd, rcv any) (err error)
}

type Svc struct {
  Client Client
}

func (svc *Svc) GetHourly(ctx context.Context, lat, lon float64) (hourly Hourly, err error) {

  var fc forecast
  err = svc.Client.SendObject(ctx, "GET", path(lat, lon), nil, &fc)
  if err != nil {
    return
  }

  hourly = fc.Hourly
  return
}

and then inject from above:

client := cfg.Client.New()
client.Use(&statusrt.StatusRt{})
client.Use(&logrt.LogRt{Logger: lgr})

weatherSvc := &svc.Svc{Client: client}
hourly, err := weatherSvc.GetHourly(ctx, lat, lon)

have a look at the example for full schnitzel.

License

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org/

Documentation

Overview

Package giant provides for reuse of comman json api client patterns while doing its best to not get in the way :)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// BaseUri is the scheme, domain, optionally port and/or path
	// though which the client connects to a webserver
	// for example: http://192.168.64.3:4080/graphql
	BaseUri string `json:"base_uri" desc:"ex: http://llp.org:4080/graphql" required:"true"`
	// Timeout is the overall request timeout
	Timeout time.Duration `json:"timeout" desc:"request timeout" default:"1m"`
	// TimeoutShort is the dialer and response header timeout
	TimeoutShort time.Duration `json:"timeout_short" desc:"dialer and header timeout" default:"10s"`
	// Headers are set when making a request
	Headers []string `json:"headers,omitempty" desc:"header pairs to be sent with every request"`
	// SkipVerify skips verification of ssl certificates (dev only pls!)
	SkipVerify bool `json:"skip_verify" desc:"skip cert verification"`
	// User is for basic auth in NewWithTrippers.
	User string `json:"user,omitempty" desc:"username for basic auth"`
	// Pass is for basic auth in NewWithTrippers.
	Pass Redact `json:"pass,omitempty" desc:"password for basic auth"`
	// RedactHeaders are headers to be redacted from logging in NewWithTrippers.
	RedactHeaders []string `json:"redact_headers,omitempty" desc:"headers to redact from request logging"`
	// SkipBody when true request and response bodies are not logged in NewWithTrippers..
	SkipBody bool `json:"skip_body" desc:"skip logging of body for request and response"`
}

Config represents giant config

func (*Config) New

func (cfg *Config) New() *Giant

New constructs a new client from Config

func (*Config) NewWithTrippers added in v0.0.2

func (cfg *Config) NewWithTrippers(lgr Logger) (giant *Giant)

NewWithTrippers is a convenience method that adds StatusRt and Logrt after creating a client. If User and Pass are defined in Config BasicRt is added as well.

type Giant

type Giant struct {
	// Client is a stdlib http client
	Client http.Client
	// BaseUri is as described in Config
	BaseUri string
	// Headers are set when making a request
	Headers map[string]string
}

Giant represents an http client

func (*Giant) Send

func (giant *Giant) Send(ctx context.Context, rq Request) (response *http.Response, err error)

Send sends a request leaving read/close of response body to caller

func (*Giant) SendJson

func (giant *Giant) SendJson(ctx context.Context, method, path string, body io.Reader) (data []byte, err error)

SendJson constructs a request, sends and recieves json closing the response body

func (*Giant) SendObject

func (giant *Giant) SendObject(ctx context.Context, method, path string, sndObj, rcvObj any) (err error)

SendObject marshalls the object to be sent, unmarshalls the response body, and calls SendJson

func (*Giant) Use

func (giant *Giant) Use(tripper Tripper)

Use wraps the current transport with a round tripper

type Logger

type Logger interface {
	Info(ctx context.Context, msg string, kv ...any)
	Error(ctx context.Context, msg string, err error, kv ...any)
	WithFields(ctx context.Context, kv ...any) context.Context
}

type Redact added in v0.0.2

type Redact string

Redact is a type for private strings

func (Redact) MarshalJSON added in v0.0.2

func (redact Redact) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface

type Request

type Request struct {
	// Method is one of the http RFC methods (no net!)
	Method string
	// Path is appended to BaseUri when making a request
	// (leading and trailing slashes recommended here, convention for sanity!)
	Path string
	// Body is read from when making a request
	Body io.Reader
	// Headers are set when making a request
	Headers map[string]string
}

Request represents an http request

type Tripper

type Tripper interface {
	http.RoundTripper
	Wrap(next http.RoundTripper)
}

Directories

Path Synopsis
Package basicrt implements the Tripper interface, adding a Basic Auth header.
Package basicrt implements the Tripper interface, adding a Basic Auth header.
examples
weather
Package main demonstrates use of a client service layer built with giant
Package main demonstrates use of a client service layer built with giant
weather/svc
Package svc demonstrates a client service layer built with giant
Package svc demonstrates a client service layer built with giant
Package logrt holds space for an implementation of http.RoundTripper that logs requests and responses.
Package logrt holds space for an implementation of http.RoundTripper that logs requests and responses.
Package statusrt implements the Tripper interface returning an error if the reponse status code is not in the 200's
Package statusrt implements the Tripper interface returning an error if the reponse status code is not in the 200's

Jump to

Keyboard shortcuts

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