httpclient

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 12 Imported by: 0

README

httpclient

The httpclient package provides a thin HTTP client wrapper. It is intended for service code that needs to send JSON, form, or raw HTTP requests without importing a larger HTTP client framework, with built-in support for query parameters, common header presets, and response decompression.

Import

import "github.com/raykavin/gobox/httpclient"

What it provides

  • NewRequestWithContext() for building and executing an HTTP request in a single call
  • DecompressResponse() for transparent body decompression based on Content-Encoding
  • MapParams type with Set and Del helpers for headers and query parameters
  • header name constants (HeaderContentType, HeaderAuthorization, etc.)
  • MIME type constants (MIMEApplicationJSON, MIMEApplicationXML, etc.)
  • header preset constructors: DefaultJSONHeaders, DefaultFormHeaders, DefaultCompressedHeaders

Main functions

  • NewRequestWithContext: builds the request, applies query params and headers, executes it, and returns the raw body bytes, HTTP status code, and any error
  • DecompressResponse: wraps http.Response.Body in a decompressing reader for gzip, deflate, Brotli, or zstd

Example

package main

import (
    "context"
    "encoding/json"
    "log"
    "net/http"

    "github.com/raykavin/gobox/httpclient"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    ctx := context.Background()

    body, status, err := httpclient.NewRequestWithContext(
        ctx,
        http.MethodGet,
        "https://jsonplaceholder.typicode.com/users",
        map[string]string{"_limit": "5"},
        httpclient.DefaultJSONHeaders(),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    if status != http.StatusOK {
        log.Fatalf("unexpected status: %d", status)
    }

    var users []User
    if err := json.Unmarshal(body, &users); err != nil {
        log.Fatal(err)
    }

    for _, u := range users {
        log.Printf("%d: %s", u.ID, u.Name)
    }
}

Decompression example

resp, err := http.Get("https://api.example.com/data")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

reader, err := httpclient.DecompressResponse(resp)
if err != nil {
    log.Fatal(err)
}
defer reader.Close()

data, _ := io.ReadAll(reader)

Notes

  • the package-level default client has a 30s timeout; pass a custom *http.Client as the last argument to NewRequestWithContext to override it
  • DecompressResponse supports gzip, deflate, br (Brotli), zstd, and identity; an unknown encoding returns an error
  • DefaultCompressedHeaders sets Accept-Encoding: gzip, deflate, br, zstd; use it together with DecompressResponse to handle compressed responses transparently

Documentation

Overview

Package httpclient provides a thin HTTP client wrapper with helpers for common header presets, query parameter encoding, and response decompression.

Sending a request

body, status, err := httpclient.NewRequestWithContext(
    ctx,
    http.MethodGet,
    "https://api.example.com/users",
    map[string]string{"page": "1"},
    httpclient.DefaultJSONHeaders(),
    nil,
)

Decompression

DecompressResponse wraps the response body in the correct reader based on the Content-Encoding header. Use it when the server returns a compressed response and you need a plain io.ReadCloser.

resp, err := http.DefaultClient.Do(req)
reader, err := httpclient.DecompressResponse(resp)
defer reader.Close()

Supported encodings: gzip, deflate, br (Brotli), zstd, and identity.

Index

Constants

View Source
const (
	HeaderContentType     = "Content-Type"
	HeaderAccept          = "Accept"
	HeaderAuthorization   = "Authorization"
	HeaderUserAgent       = "User-Agent"
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderContentEncoding = "Content-Encoding"
	HeaderCacheControl    = "Cache-Control"
	HeaderXRequestID      = "X-Request-Id"
)

Header name constants.

View Source
const (
	MIMEApplicationJSON           = "application/json"
	MIMEApplicationXML            = "application/xml"
	MIMEApplicationFormURLEncoded = "application/x-www-form-urlencoded"
	MIMEMultipartFormData         = "multipart/form-data"
	MIMETextPlain                 = "text/plain; charset=utf-8"
	MIMEOctetStream               = "application/octet-stream"
)

MIME type constants.

View Source
const (
	CacheControlNoCache = "no-cache"
	CacheControlNoStore = "no-store"
	CacheControlMaxAge0 = "max-age=0"
)

Cache-Control directive constants.

View Source
const AcceptEncodingAll = "gzip, deflate, br, zstd"

AcceptEncodingAll declares support for all encodings implemented in DecompressResponse. Use alongside DecompressResponse.

Variables

This section is empty.

Functions

func DecompressResponse

func DecompressResponse(r *http.Response) (io.ReadCloser, error)

DecompressResponse wraps the response body in the appropriate decompression reader based on the Content-Encoding header. The caller is responsible for closing the returned reader.

func NewRequestWithContext

func NewRequestWithContext(
	ctx context.Context,
	method string,
	urlStr string,
	queryParams map[string]string,
	headers map[string]string,
	payload []byte,
	client ...*http.Client,
) ([]byte, int, error)

NewRequestWithContext builds and executes an HTTP request, returning the raw response body, the status code, and any error. Decompression is not applied automatically use DecompressResponse if needed.

Types

type MapParams

type MapParams map[string]string

MapParams is a map type used by this package for request headers and query parameters.

func DefaultCompressedHeaders

func DefaultCompressedHeaders() MapParams

DefaultCompressedHeaders returns a new map that advertises support for all compressed encodings. Use alongside DecompressResponse.

func DefaultFormHeaders

func DefaultFormHeaders() MapParams

DefaultFormHeaders returns a new map with standard form-encoded request headers.

func DefaultJSONHeaders

func DefaultJSONHeaders() MapParams

DefaultJSONHeaders returns a new map with standard JSON request headers.

func (MapParams) Del

func (m MapParams) Del(k string)

Del removes k from the map if it exists.

func (MapParams) Set

func (m MapParams) Set(k, v string)

Set assigns v to k in the map. The receiver must be initialized before calling Set.

Jump to

Keyboard shortcuts

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