ezhttp

package
v0.0.0-...-a5f7211 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: Apache-2.0 Imports: 10 Imported by: 13

Documentation

Overview

This package aims to wrap Go HTTP Client's request-response with sane defaults:

  • You are forced to consider timeouts by having to specify Context
  • Instead of not considering non-2xx status codes as a failure, check that by default (unless explicitly asked to)
  • Sending and receiving JSON requires much less boilerplate, and on receiving JSON you are forced to think whether to "allowUnknownFields"

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultTimeout10s = 10 * time.Second
	NoOpConfig        = ConfigPiece{} // sometimes it's beneficial to give an option that does nothing (so user doesn't have to do varargs)
)
View Source
var EnableTLSKeyLog = After(func(conf *Config) {
	keyLoggingClientCachedMu.Lock()
	defer keyLoggingClientCachedMu.Unlock()

	if keyLoggingClientCached == nil {

		keyLogWriter, err := func() (io.Writer, error) {
			if name := os.Getenv("SSLKEYLOGFILE"); name != "" {
				return os.Create(name)
			} else {
				return nil, nil
			}
		}()
		if err != nil {

			panic(fmt.Errorf("SSLKEYLOGFILE requested but: %w", err))
		}

		keyLoggingClientCached = func() *http.Client {
			if keyLogWriter != nil {
				return &http.Client{
					Transport: &http.Transport{

						TLSClientConfig: &tls.Config{
							KeyLogWriter: keyLogWriter,
						},
					},
				}
			} else {
				return http.DefaultClient
			}
		}()
	}

	conf.Client = keyLoggingClientCached
})

opt-in for logging TLS secrets to file specified in SSLKEYLOGFILE ENV var. if logging is not requested, uses http.DefaultClient

View Source
var InsecureTlsClient = &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{

			InsecureSkipVerify: true,
		},
	},
}
View Source
var TolerateNon2xxResponse = After(func(conf *Config) {
	conf.TolerateNon2xxResponse = true
})

Functions

func Del

func Del(ctx context.Context, url string, confPieces ...ConfigPiece) (*http.Response, error)

returns *ResponseStatusError as error if non-2xx response (unless TolerateNon2xxResponse()). error is not *ResponseStatusError for transport-level errors, content (JSON) marshaling errors etc

func ErrorIs

func ErrorIs(err error, statusCode int) bool

checks if "err" is *ResponseStatusError and has "statusCode" status

func Get

func Get(ctx context.Context, url string, confPieces ...ConfigPiece) (*http.Response, error)

returns *ResponseStatusError as error if non-2xx response (unless TolerateNon2xxResponse()). error is not *ResponseStatusError for transport-level errors, content (JSON) marshaling errors etc

func Head(ctx context.Context, url string, confPieces ...ConfigPiece) (*http.Response, error)

returns *ResponseStatusError as error if non-2xx response (unless TolerateNon2xxResponse()). error is not *ResponseStatusError for transport-level errors, content (JSON) marshaling errors etc

func Post

func Post(ctx context.Context, url string, confPieces ...ConfigPiece) (*http.Response, error)

returns *ResponseStatusError as error if non-2xx response (unless TolerateNon2xxResponse()). error is not *ResponseStatusError for transport-level errors, content (JSON) marshaling errors etc

func Put

func Put(ctx context.Context, url string, confPieces ...ConfigPiece) (*http.Response, error)

returns *ResponseStatusError as error if non-2xx response (unless TolerateNon2xxResponse()). error is not *ResponseStatusError for transport-level errors, content (JSON) marshaling errors etc

Types

type Config

type Config struct {
	Abort                         error // ConfigHook can set this to abort request send
	Client                        *http.Client
	Request                       *http.Request
	TolerateNon2xxResponse        bool
	RequestBody                   io.Reader
	OutputsJson                   bool
	OutputsJsonRef                interface{}
	OutputsJsonAllowUnknownFields bool
}

func NewDel

func NewDel(ctx context.Context, url string, confPieces ...ConfigPiece) *Config

same as the corresponding without "New" prefix, but just prepared the request configuration without sending it yet

func NewGet

func NewGet(ctx context.Context, url string, confPieces ...ConfigPiece) *Config

same as the corresponding without "New" prefix, but just prepared the request configuration without sending it yet

func NewHead

func NewHead(ctx context.Context, url string, confPieces ...ConfigPiece) *Config

same as the corresponding without "New" prefix, but just prepared the request configuration without sending it yet

func NewPost

func NewPost(ctx context.Context, url string, confPieces ...ConfigPiece) *Config

same as the corresponding without "New" prefix, but just prepared the request configuration without sending it yet

func NewPut

func NewPut(ctx context.Context, url string, confPieces ...ConfigPiece) *Config

same as the corresponding without "New" prefix, but just prepared the request configuration without sending it yet

func (*Config) CURLEquivalent

func (c *Config) CURLEquivalent() ([]string, error)

for `method` please use `net/http` "enum" (quotes because it's not declared as such)

func (*Config) Send

func (conf *Config) Send() (*http.Response, error)

type ConfigHook

type ConfigHook func(conf *Config)

type ConfigPiece

type ConfigPiece struct {
	BeforeInit ConfigHook
	AfterInit  ConfigHook
}

func After

func After(fn ConfigHook) ConfigPiece

func AuthBasic

func AuthBasic(username, password string) ConfigPiece

func AuthBearer

func AuthBearer(token string) ConfigPiece

func Before

func Before(fn ConfigHook) ConfigPiece

same as After(), but Config.Request is nil. used mainly for specifying request body, which must be known on call to http.NewRequest()

func Client

func Client(client *http.Client) ConfigPiece
func Cookie(cookie http.Cookie) ConfigPiece
func Header(key, val string) ConfigPiece

func RespondsJSONAllowUnknownFields

func RespondsJSONAllowUnknownFields(obj interface{}) ConfigPiece

use this when you want to be forward compatible, i.e. server is allowed to add new fields to JSON structure.

func RespondsJSONDisallowUnknownFields

func RespondsJSONDisallowUnknownFields(obj interface{}) ConfigPiece

use this when you DON'T want to be forward compatible, i.e. server is not allowed to add new fields to JSON structure without yielding an error.

func RespondsJson deprecated

func RespondsJson(ref interface{}, allowUnknownFields bool) ConfigPiece

Deprecated: use explicit allow/disallow instead

func RespondsJsonAllowUnknownFields deprecated

func RespondsJsonAllowUnknownFields(obj interface{}) ConfigPiece

Deprecated: use fn with JSON uppercased

func RespondsJsonDisallowUnknownFields deprecated

func RespondsJsonDisallowUnknownFields(obj interface{}) ConfigPiece

Deprecated: use fn with JSON uppercased

func SendBody

func SendBody(body io.Reader, contentType string) ConfigPiece

func SendJSON

func SendJSON(ref interface{}) ConfigPiece

func SendJson deprecated

func SendJson(ref interface{}) ConfigPiece

Deprecated: use fn with JSON uppercased

type ResponseStatusError

type ResponseStatusError struct {
	// contains filtered or unexported fields
}

func (ResponseStatusError) StatusCode

func (e ResponseStatusError) StatusCode() int

returns the (non-2xx) status code that caused the error

Jump to

Keyboard shortcuts

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