httputil

package
v1.157.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 19 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httputil

Go Reference

Package httputil provides HTTP request/response primitives for Go services built on top of net/http.

The package groups helpers by role:

  • request helpers: header decorators, path/query/header default extraction, request-time context utilities
  • response helpers: text/JSON/XML/problem+json responses with no-cache and nosniff headers, full-buffer encoding with a 500 fallback on marshal failure, and structured response logging via HTTPResp
  • response-writer wrapper: status/size capture and optional tee support for middleware instrumentation (ResponseWriterWrapper)
  • URL composition helper for link building (Link)

Response logs contain code, duration, timestamp, trace ID, and payload metadata, logged by class (2xx debug, 4xx warn, 5xx error). JSend-style status projection and round-trip parsing are provided by StatusSuccess, StatusFail, StatusError, Status.UnmarshalJSON, and ErrInvalidStatus. RFC 9457 Problem Details error documents are provided by Problem, NewProblem and HTTPResp.SendProblem, with router fallbacks in the same format via HTTPResp.ProblemNotFoundHandlerFunc, HTTPResp.ProblemMethodNotAllowedHandlerFunc and HTTPResp.ProblemPanicHandlerFunc. Any other JSON-based media type is reachable through HTTPResp.SendJSONType. Reason phrases come from StatusText, which covers non-standard status codes with their status class name.

When To Use

  • You are writing handlers against net/http and want consistent request parsing and response writing.
  • Responses should follow one envelope across every endpoint.

Example

// A trusted, compile-time template is used as a fmt.Sprintf format string.
fmt.Println(httputil.Link("https://api.example.invalid", "users/%s", "42"))

// Untrusted string segments must be escaped by the caller to avoid injecting
// path or query delimiters.
fmt.Println(httputil.Link("https://api.example.invalid", "users/%s", url.PathEscape("a/b?c")))

// Output:
// https://api.example.invalid/users/42
// https://api.example.invalid/users/a%2Fb%3Fc

Full source is in example_httputil_test.go. More runnable examples are on pkg.go.dev.

Dependencies

Importing this package pulls 1 external module:

  • github.com/julienschmidt/httprouter

Documentation

Overview

Package httputil provides HTTP request/response primitives for Go services built on top of net/http.

The package groups helpers by role:

  • request helpers: header decorators, path/query/header default extraction, request-time context utilities
  • response helpers: text/JSON/XML/problem+json responses with no-cache and nosniff headers, full-buffer encoding with a 500 fallback on marshal failure, and structured response logging via HTTPResp
  • response-writer wrapper: status/size capture and optional tee support for middleware instrumentation (ResponseWriterWrapper)
  • URL composition helper for link building (Link)

Response logs contain code, duration, timestamp, trace ID, and payload metadata, logged by class (2xx debug, 4xx warn, 5xx error). JSend-style status projection and round-trip parsing are provided by StatusSuccess, StatusFail, StatusError, Status.UnmarshalJSON, and ErrInvalidStatus. RFC 9457 Problem Details error documents are provided by Problem, NewProblem and HTTPResp.SendProblem, with router fallbacks in the same format via HTTPResp.ProblemNotFoundHandlerFunc, HTTPResp.ProblemMethodNotAllowedHandlerFunc and HTTPResp.ProblemPanicHandlerFunc. Any other JSON-based media type is reachable through HTTPResp.SendJSONType. Reason phrases come from StatusText, which covers non-standard status codes with their status class name.

When To Use

  • You are writing handlers against net/http and want consistent request parsing and response writing.
  • Responses should follow one envelope across every endpoint.

Index

Examples

Constants

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderAuthBasic     = "Basic "
	HeaderAuthBearer    = "Bearer "
	HeaderContentType   = "Content-Type"
	HeaderAccept        = "Accept"
	MimeTypeJSON        = "application/json"
)

Common HTTP headers and MIME types.

View Source
const (
	// MimeApplicationJSON contains the mime type string for JSON content.
	MimeApplicationJSON = "application/json; charset=utf-8"

	// MimeApplicationXML contains the mime type string for XML content.
	MimeApplicationXML = "application/xml; charset=utf-8"

	// MimeApplicationProblemJSON contains the mime type string for RFC 9457 problem
	// details content. Unlike the other mime constants it carries no charset
	// parameter: RFC 9457 registers the media type without one.
	MimeApplicationProblemJSON = "application/problem+json"

	// MimeTextPlain contains the mime type string for text content.
	MimeTextPlain = "text/plain; charset=utf-8"
)
View Source
const (
	StatusSuccess = "success"
	StatusFail    = "fail"
	StatusError   = "error"
)

JSend status codes.

View Source
const ProblemTypeBlank = "about:blank"

ProblemTypeBlank is the problem type URI used when no type is given.

View Source
const ReqTimeCtxKey = timeCtxKey("request_time")

ReqTimeCtxKey is the Context key to retrieve the request time.

View Source
const XMLHeader = xml.Header

XMLHeader is a default XML Declaration header suitable for use with the SendXML function.

Variables

View Source
var ErrInvalidStatus = errors.New("invalid JSend status")

ErrInvalidStatus is returned when unmarshaling a JSend status value that is not one of "success", "fail", or "error".

Functions

func AddAuthorizationHeader

func AddAuthorizationHeader(auth string, r *http.Request)

AddAuthorizationHeader sets the Authorization header to the specified value, replacing any previously set value. The Authorization header is a singleton per RFC 9110 §11.6.2, so repeated calls (e.g. refreshing a token before a retry) must not accumulate multiple values.

func AddBasicAuth

func AddBasicAuth(apiKey, apiSecret string, r *http.Request)

AddBasicAuth adds Basic Authorization header with base64-encoded "apiKey:apiSecret" credentials.

Per RFC 7617 the user-id (apiKey) must not contain a colon, as the first colon separates the user-id from the password when the credentials are decoded.

func AddBearerToken

func AddBearerToken(token string, r *http.Request)

AddBearerToken adds Bearer Authorization header with the provided token.

func AddJSONHeaders

func AddJSONHeaders(r *http.Request)

AddJSONHeaders sets application/json Accept and Content-Type headers on the request.

func GetRequestTime

func GetRequestTime(r *http.Request) (time.Time, bool)

GetRequestTime returns the request time from the http request.

func GetRequestTimeFromContext

func GetRequestTimeFromContext(ctx context.Context) (time.Time, bool)

GetRequestTimeFromContext retrieves request timestamp from context, returning zero time if not present.

func HeaderOrDefault

func HeaderOrDefault(r *http.Request, key string, defaultValue string) string

HeaderOrDefault returns the HTTP header value, or defaultValue if the header is missing or set to the empty string.

func Link(url, template string, segments ...any) string

Link composes URL by substituting template segments using fmt.Sprintf and appending to service URL.

A trailing slash on url and a leading slash on template are trimmed so exactly one separator joins them.

When segments are provided, template is used as a fmt.Sprintf format string. For this reason template MUST be a trusted, compile-time constant format string controlled by the caller. Never pass an externally-derived or user-supplied value as template, as it would be interpreted as a format string (a format-string injection footgun).

Segments are not URL-escaped: callers passing untrusted string segments must escape them (e.g. with url.PathEscape) to avoid injecting path or query delimiters. Note also that a literal "%" in template is emitted verbatim when no segments are given but interpreted as a fmt verb once any segment is passed.

func PathParam

func PathParam(r *http.Request, name string) string

PathParam returns the value of a named path segment from httprouter params in request context.

httprouter prefixes catch-all parameters with a single "/"; only that router-added slash is stripped, so slashes that are part of the client-supplied value are preserved.

func QueryIntOrDefault

func QueryIntOrDefault(q url.Values, key string, defaultValue int) int

QueryIntOrDefault parses query parameter as signed integer or returns defaultValue if missing or invalid.

Example
package main

import (
	"fmt"
	"net/url"

	"github.com/tecnickcom/nurago/pkg/httputil"
)

func main() {
	q := url.Values{"limit": []string{"25"}}

	fmt.Println(httputil.QueryIntOrDefault(q, "limit", 10))
	fmt.Println(httputil.QueryIntOrDefault(q, "missing", 10))

}
Output:
25
10

func QueryStringOrDefault

func QueryStringOrDefault(q url.Values, key string, defaultValue string) string

QueryStringOrDefault returns query parameter value or defaultValue if missing or empty.

func QueryUintOrDefault

func QueryUintOrDefault(q url.Values, key string, defaultValue uint) uint

QueryUintOrDefault parses query parameter as unsigned integer or returns defaultValue if missing or invalid.

func StatusText added in v1.155.0

func StatusText(statusCode int) string

StatusText returns the standard reason phrase for statusCode, falling back to the name of its RFC 9110 status class when net/http knows no phrase for the code.

http.StatusText returns an empty string for non-standard codes such as 499 or 529, which would leave a response body, log entry or message field with no description of the status at all. Codes outside the 100-599 range yield "Unknown Status".

func StringValueOrDefault

func StringValueOrDefault(v, def string) string

StringValueOrDefault returns the string value or a default value.

func WithRequestTime

func WithRequestTime(ctx context.Context, t time.Time) context.Context

WithRequestTime returns new context with request timestamp attached via ReqTimeCtxKey.

Types

type HTTPResp

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

HTTPResp holds the configuration for the HTTP response methods.

func NewHTTPResp

func NewHTTPResp(l *slog.Logger) *HTTPResp

NewHTTPResp constructs HTTP response helper with structured logging to provided logger (or slog.Default() if nil).

Example
package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/tecnickcom/nurago/pkg/httputil"
)

func main() {
	// The logger is where structured response entries go; the body is written to w.
	res := httputil.NewHTTPResp(slog.New(slog.DiscardHandler))

	rr := httptest.NewRecorder()
	res.SendJSON(context.Background(), rr, http.StatusOK, struct {
		Message string `json:"message"`
	}{Message: "hello"})

	fmt.Print(rr.Body.String())

}
Output:
{"message":"hello"}

func (*HTTPResp) ProblemMethodNotAllowedHandlerFunc added in v1.155.0

func (hr *HTTPResp) ProblemMethodNotAllowedHandlerFunc(typeURI string) http.HandlerFunc

ProblemMethodNotAllowedHandlerFunc returns the handler used when a route exists but the method is not allowed, answering in RFC 9457 format.

func (*HTTPResp) ProblemNotFoundHandlerFunc added in v1.155.0

func (hr *HTTPResp) ProblemNotFoundHandlerFunc(typeURI string) http.HandlerFunc

ProblemNotFoundHandlerFunc returns the handler used when no route matches, answering in RFC 9457 format.

func (*HTTPResp) ProblemPanicHandlerFunc added in v1.155.0

func (hr *HTTPResp) ProblemPanicHandlerFunc(typeURI string) http.HandlerFunc

ProblemPanicHandlerFunc returns the handler for recovered panics, answering in RFC 9457 format.

func (*HTTPResp) SendJSON

func (hr *HTTPResp) SendJSON(ctx context.Context, w http.ResponseWriter, statusCode int, data any)

SendJSON encodes data as JSON, writes with cache-control headers, and logs response entry.

The payload is marshaled fully before any header or status code is written, so a marshaling failure produces a clean 500 Internal Server Error instead of a partial or empty body sent under the requested (success) status code.

func (*HTTPResp) SendJSONType added in v1.155.0

func (hr *HTTPResp) SendJSONType(
	ctx context.Context,
	w http.ResponseWriter,
	statusCode int,
	contentType string,
	data any,
)

SendJSONType encodes data as JSON with a caller-supplied content type, writes it with cache-control headers, and logs the response entry.

It serves JSON-based media types that have no dedicated method, such as application/ld+json or any application/vnd.*+json variant. Use HTTPResp.SendJSON for application/json and HTTPResp.SendProblem for application/problem+json.

The payload is marshaled fully before any header or status code is written, so a marshaling failure produces a clean 500 Internal Server Error instead of a partial or empty body sent under the requested (success) status code.

func (*HTTPResp) SendProblem added in v1.155.0

func (hr *HTTPResp) SendProblem(ctx context.Context, w http.ResponseWriter, statusCode int, data any)

SendProblem encodes data as an RFC 9457 problem details document, writes it with cache-control headers, and logs the response entry.

The data payload is typically a Problem or a struct embedding one. It is marshaled fully before any header or status code is written, so a marshaling failure produces a clean 500 Internal Server Error instead of a partial body.

Example
package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/tecnickcom/nurago/pkg/httputil"
)

func main() {
	// Extension members are added by embedding Problem in an outer struct; the
	// promoted fields stay inline in the encoded object.
	type conflict struct {
		httputil.Problem

		ConflictingBookingID string `json:"conflicting_booking_id"`
	}

	res := httputil.NewHTTPResp(slog.New(slog.DiscardHandler))

	rr := httptest.NewRecorder()
	res.SendProblem(context.Background(), rr, http.StatusConflict, conflict{
		Problem:              httputil.NewProblem(http.StatusConflict, "", "", "slot already booked"),
		ConflictingBookingID: "b-17",
	})

	fmt.Println(rr.Header().Get("Content-Type"))
	fmt.Print(rr.Body.String())

}
Output:
application/problem+json
{"type":"about:blank","title":"Conflict","status":409,"detail":"slot already booked","conflicting_booking_id":"b-17"}

func (*HTTPResp) SendStatus

func (hr *HTTPResp) SendStatus(ctx context.Context, w http.ResponseWriter, statusCode int)

SendStatus writes HTTP status code with standard text and logs response entry.

The body is the reason phrase from StatusText, so a non-standard status code still produces a description instead of an empty line.

func (*HTTPResp) SendText

func (hr *HTTPResp) SendText(ctx context.Context, w http.ResponseWriter, statusCode int, data string)

SendText writes plain text response with cache-control headers and structured logging.

func (*HTTPResp) SendXML

func (hr *HTTPResp) SendXML(ctx context.Context, w http.ResponseWriter, statusCode int, xmlHeader string, data any)

SendXML encodes data as XML with header prefix, cache-control headers, and structured logging.

The document (declaration header plus encoded payload) is buffered fully before any header or status code is written, so an encoding failure produces a clean 500 Internal Server Error instead of a truncated document under a success status code.

type Problem added in v1.155.0

type Problem struct {
	// Type is a URI reference identifying the problem type.
	Type string `json:"type"`

	// Title is a short human-readable summary of the problem type, constant for a given Type.
	// It is omitted when empty, as RFC 9457 makes it optional and an empty summary carries
	// no more information than an absent one.
	Title string `json:"title,omitempty"`

	// Status is the HTTP status code.
	Status int `json:"status,omitempty"`

	// Detail is a human-readable explanation specific to this occurrence.
	Detail string `json:"detail,omitempty"`

	// Instance is a URI reference identifying this specific occurrence.
	Instance string `json:"instance,omitempty"`
}

Problem is an RFC 9457 Problem Details object.

Extension members are added by embedding Problem in an outer struct. Problem has no MarshalJSON method so the promoted fields stay inline in the encoded object; adding one would shadow the outer struct's own fields.

func NewProblem added in v1.155.0

func NewProblem(statusCode int, typeURI, title, detail string) Problem

NewProblem returns a Problem for statusCode.

An empty typeURI is replaced with ProblemTypeBlank and an empty title with the standard status text for statusCode, which is what RFC 9457 prescribes for the about:blank type. Title stays empty, and is then omitted from the encoded document, for status codes net/http has no text for. Instance is left empty for the caller to set, as it identifies a single occurrence and usually derives from the request.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/tecnickcom/nurago/pkg/httputil"
)

func main() {
	p := httputil.NewProblem(http.StatusConflict, "", "", "slot already booked")
	p.Instance = "/bookings/42"

	// An empty type URI becomes about:blank and an empty title the status text.
	fmt.Printf("%s | %s | %d\n", p.Type, p.Title, p.Status)

}
Output:
about:blank | Conflict | 409

type ResponseWriterWrapper

type ResponseWriterWrapper interface {
	http.ResponseWriter

	// Size returns the total number of bytes sent to the client.
	Size() int

	// Status returns the HTTP response status code written to the client.
	// It returns 0 until the header is written; callers that need the effective
	// value should treat 0 as the implicit 200 that net/http sends.
	Status() int

	// Tee sets a writer that receives a copy of the bytes written to the response
	// writer. Only bytes written after this call are copied. A tee-write failure is
	// surfaced as the error return of Write, after the client bytes have already
	// been sent. Setting a tee also routes ReadFrom through a generic copy,
	// disabling any io.ReaderFrom (sendfile) fast path on the underlying writer.
	Tee(w io.Writer)
}

ResponseWriterWrapper augments http.ResponseWriter with status/size tracking and tee support.

func NewResponseWriterWrapper

func NewResponseWriterWrapper(w http.ResponseWriter) ResponseWriterWrapper

NewResponseWriterWrapper wraps http.ResponseWriter with status/size capture and optional tee support.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/tecnickcom/nurago/pkg/httputil"
)

func main() {
	// Middleware wraps the writer to observe the status and byte size a handler produced.
	rr := httptest.NewRecorder()
	ww := httputil.NewResponseWriterWrapper(rr)

	ww.WriteHeader(http.StatusCreated)
	_, _ = ww.Write([]byte("created"))

	fmt.Printf("status=%d size=%d\n", ww.Status(), ww.Size())

}
Output:
status=201 size=7

type Status

type Status int

Status translates the HTTP status code to a JSend status string.

The value-receiver String/MarshalJSON and pointer-receiver UnmarshalJSON mix is required: UnmarshalJSON must mutate the receiver, while String/MarshalJSON must work on non-addressable values.

func (Status) MarshalJSON

func (sc Status) MarshalJSON() ([]byte, error)

MarshalJSON implements the custom marshaling function for the json encoder, emitting the JSend status string (see Status.String). Because Status also implements fmt.Stringer, slog text handlers render the same string.

func (Status) String

func (sc Status) String() string

String projects the HTTP status code onto a JSend status string:

  • codes below 400 (including 0 and negative values) map to "success"
  • codes in the 400-499 range map to "fail"
  • codes 500 and above map to "error"

func (*Status) UnmarshalJSON

func (sc *Status) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the custom unmarshaling function for the json decoder.

A JSend status string is mapped back to a representative HTTP status code. The mapping is intentionally lossy: the original code is not recoverable from the status string alone and should be read from the accompanying code field (e.g. jsendx.Response.Code):

  • "success" maps to 200 (http.StatusOK)
  • "fail" maps to 400 (http.StatusBadRequest)
  • "error" maps to 500 (http.StatusInternalServerError)

Any other value yields ErrInvalidStatus.

Directories

Path Synopsis
Package jsendx implements an extended JSend response envelope for HTTP APIs.
Package jsendx implements an extended JSend response envelope for HTTP APIs.

Jump to

Keyboard shortcuts

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