Skip to content
/ httpc Public

A simple wrapper around the default Go http client optimized for ease-of-use

License

Notifications You must be signed in to change notification settings

fako1024/httpc

Repository files navigation

A simple wrapper around the default Go http client optimized for ease-of-use

Github Release GoDoc Go Report Card Build/Test Status CodeQL

This package wraps the Go standard http client, providing a simplified interaction model using method chaining and additional capabilities such as optional in-flow validation against an OpenAPI specification.

Features

  • Simple, method chaining based interface for HTTP client requests
  • Simulation of request delays
  • Validation of request + response against OpenAPI specification
  • Customization of HTTP client via functional parameter
  • Back-Off-Retry concept to automatically retry requests if required

Installation

go get -u github.com/fako1024/httpc

Examples

Perform simple HTTP GET request

err := httpc.New("GET", "http://example.org").Run()
if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}

Perform HTTP GET request and parse the result as JSON into a struct

var res = struct {
	Status int
	Message string
}{}
err := httpc.New("GET", "http://example.org").
	ParseJSON(&res).
	Run()
if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}

Perform HTTPS POST request with a simple body, disabling certificate validation and copying the response to a bytes.Buffer

buf := new(bytes.Buffer)
err := httpc.New("POST", "https://example.org").
	SkipCertificateVerification().
	Body([]byte{0x1, 0x2}).
	ParseFn(httpc.Copy(buf)).
	Run()

if err != nil {
    log.Fatalf("error performing POST request: %s", err)
}

fmt.Println(buf.String())

Perform HTTPS GET request (with query parameters + headers + basic auth), validating request and response against OpenAPIv3 specification

openAPIFileData, err := os.ReadFile("/tmp/openapi.json")
if err != nil {
	log.Fatalf("Error opening OpenAPI specification file: %s", err)
}

err = httpc.New("GET", "https://example.org").
	SkipCertificateVerification().
	QueryParams(httpc.Params{
		"param": "test",
	}).
	Headers(httpc.Params{
		"X-HEADER-TEST": "test",
	}).
	AuthBasic("username", "password").
	OpenAPIValidationFileData(openAPIFileData).
	Run()

if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}