giant

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: Unlicense Imports: 18 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 common 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" default:"false"`
	// Ciphers overrides default tls ciphers
	Ciphers []uint16 `json:"ciphers" desc:"ciphers override"`
	// 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 launch.Redact `json:"pass,omitempty" desc:"password for basic auth"`
	// Todo: what's this??
	//KeyHeader string `json:"api_key_header,omitempty" desc:"Todo"`
	//ApiKey    Redact `json:"api_key_value,omitempty" desc:"Todo and sneak into redact headers"`
	// Todo: orrrrrrrr a giant client helper in bfc would work?
	// 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" default:"false"`
	// UnixSocket
	UnixSocket string `json:"unix_socket,omitempty" desc:"unix socket"`
	// OAuth2 is for OAuth2 client credentials in NewWithTrippers.
	OAuth2 *OAuth2Config `json:"oauth2,omitempty" desc:"OAuth2 client credentials config"`
}

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.Logger) (giant *Giant)

NewWithTrippers is a convenience method that adds StatusRt and Logrt after creating a client. If OAuth2 is defined in Config OAuth2Rt is added as well. 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 receives 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) Uri added in v0.0.8

func (giant *Giant) Uri() string

Uri returns the base uri for use in links, etc.

func (*Giant) Use

func (giant *Giant) Use(tripper tripper)

Use wraps the current transport with a round tripper

type OAuth2Config added in v0.0.9

type OAuth2Config struct {
	// BaseUri is the OAuth2 token endpoint base URI.
	// If empty, defaults to Config.BaseUri.
	BaseUri string `json:"base_uri,omitempty" desc:"OAuth2 base URI (defaults to client base_uri)"`
	// TokenPath is the path to the token endpoint.
	TokenPath string `json:"token_path" desc:"path to token endpoint" default:"/oauth/token"`
	// ClientID is the OAuth2 client ID.
	ClientID string `json:"client_id" desc:"OAuth2 client ID"`
	// ClientSecret is the OAuth2 client secret.
	ClientSecret launch.Redact `json:"client_secret" desc:"OAuth2 client secret or path to secret file"`
}

OAuth2Config represents OAuth2 client credentials configuration.

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

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
oauth2 command
Package main demonstrates use of oauth2rt with giant
Package main demonstrates use of oauth2rt with giant
weather command
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 logger defines the logging interface for giant.
Package logger defines the logging interface for 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 oauth2rt implements the Tripper interface for OAuth2 client credentials.
Package oauth2rt implements the Tripper interface for OAuth2 client credentials.
Package statusrt implements the Tripper interface returning an error if the response status code is not in the 200's
Package statusrt implements the Tripper interface returning an error if the response 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