httpresponse

package
v1.8.30 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 17 Imported by: 9 modules, 57 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.

Documentation

Index

Constants

View Source
const (
	ErrBadRequest         = Err(http.StatusBadRequest)
	ErrNotFound           = Err(http.StatusNotFound)
	ErrConflict           = Err(http.StatusConflict)
	ErrNotImplemented     = Err(http.StatusNotImplemented)
	ErrInternalError      = Err(http.StatusInternalServerError)
	ErrNotAuthorized      = Err(http.StatusUnauthorized)
	ErrForbidden          = Err(http.StatusForbidden)
	ErrServiceUnavailable = Err(http.StatusServiceUnavailable)
	ErrGatewayError       = Err(http.StatusBadGateway)
)

Variables

This section is empty.

Functions

func Empty

func Empty(w http.ResponseWriter, code int) error

Empty is a utility function to serve an empty response

func Error

func Error(w http.ResponseWriter, err error, detail ...any) error

Error writes an error from a HTTP status code, with additional detail

func JSON

func JSON(w http.ResponseWriter, code, indent int, v any) error

JSON will write a JSON response to the writer with a HTTP status code, optionally indenting the JSON by a number of spaces

func NewJSONStreamHandler added in v1.6.24

func NewJSONStreamHandler(fn JSONStreamHandlerFunc, headers ...string) http.Handler

NewJSONStreamHandler wraps a channel-based handler function in an HTTP handler. The receive channel yields compacted JSON frames from the request body and nil for heartbeat lines. Sending nil on the write channel emits a blank heartbeat line.

func Write

func Write(w http.ResponseWriter, code int, contentType string, fn func(w io.Writer) (int, error)) error

Write a custom response to the writer with a HTTP status code. If the custom function is set and returns the number of bytes written (greater than zero), it will be used to write the response body.

Types

type Binary added in v1.7.15

type Binary struct {
	// ContentType is the Content-Type, which is application/octet-stream when
	// it's empty
	ContentType string

	// Size is the Content-Length, when it's known
	Size *int64

	// ModTime is the Last-Modified time, when it isn't zero
	ModTime time.Time

	// ETag is the entity tag, without quotes, when it isn't empty
	ETag string

	// Path is the path of the content, whose file name is in the
	// Content-Disposition, when it isn't empty
	Path string

	// Disposition is how the browser presents the content, which is in the
	// Content-Disposition, with the file name, when it isn't empty
	Disposition Disposition

	// CacheControl is how the response is cached, which is private,
	// no-cache when it's the zero value
	CacheControl CacheControl

	// Meta is the metadata of the content, as JSON in the X-Meta header, when
	// it isn't nil
	Meta any
}

Binary describes content, such as a file, for its response

func (Binary) NotModified added in v1.7.15

func (b Binary) NotModified(r *http.Request) bool

NotModified returns true when a GET or HEAD request's If-None-Match has the content's etag, by weak comparison, or is *, or without If-None-Match, the content hasn't been modified since If-Modified-Since, to the second, as HTTP dates are. An If-None-Match which can't be parsed doesn't match.

func (Binary) Write added in v1.7.15

func (b Binary) Write(w http.ResponseWriter, r *http.Request, body io.Reader) error

Write responds with the content's headers, and for a GET request, its content, read from body. The request's preconditions are evaluated in the order of RFC 9110: when If-Match, or without it, If-Unmodified-Since, fails, it's 412 Precondition Failed, and when the content isn't modified (see NotModified), it's 304 Not Modified, with its headers. For a HEAD request it's its headers alone, and for a GET request without a body, 204 No Content. Otherwise its content is written without the server's write timeout, as a large file, or a video a browser reads as it plays it, can take longer, in ranges when body can seek, such as a file.

The content isn't sniffed as another type, and content which can run scripts in a browser, which is HTML and XML, including SVG, is sandboxed, so it can't run scripts with access to the server. Other types aren't, as a browser shows media and PDFs in a page of its own, which can't load them when it's sandboxed.

Returns an error, without writing the response, when the headers can't be set, and otherwise any error reading or writing the content, after which the response can't be changed.

type CacheControl added in v1.7.15

type CacheControl struct {
	// Public is true when a shared cache, such as a proxy or a CDN, can keep
	// the response, rather than only the browser
	Public bool

	// MaxAge is how long the response is used without checking it hasn't
	// changed, to the second, or when it's zero, it's always checked
	MaxAge time.Duration

	// Immutable is true when the response never changes, so it isn't checked
	// when the page is reloaded, while it's within MaxAge, such as content
	// whose etag is its hash
	Immutable bool

	// NoStore is true when the response isn't kept at all, such as sensitive
	// data, which overrides the others
	NoStore bool
}

CacheControl is how a response is cached, in its Cache-Control header. The zero value is private, no-cache: a browser can keep the response, but must check it hasn't changed before using it, and a shared cache, such as a proxy, doesn't keep it, which is safe for content which can change, or needs authentication.

func (CacheControl) String added in v1.7.15

func (c CacheControl) String() string

String returns the value of the Cache-Control header

type DeadlineWriter added in v1.8.0

type DeadlineWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

DeadlineWriter writes a stream to a client, such as of server-sent events, with a deadline for each write, rather than the server's write timeout, which is for the whole response, so a client which stops reading can't block it for longer than the timeout, and its Failed channel is closed when a write fails

func NewDeadlineWriter added in v1.8.0

func NewDeadlineWriter(w http.ResponseWriter, timeout time.Duration) (*DeadlineWriter, error)

NewDeadlineWriter returns a writer of a stream to a client, with the timeout of each write, and clears the server's deadline of the whole response, unless the response writer can't have its deadline set, when it's streamed to until the server's timeout

func (*DeadlineWriter) Failed added in v1.8.0

func (w *DeadlineWriter) Failed() <-chan struct{}

Failed returns a channel which is closed when a write fails, as the client stopped reading, or went away

func (*DeadlineWriter) Flush added in v1.8.0

func (w *DeadlineWriter) Flush()

Flush sends what's written to the client, by the deadline

func (*DeadlineWriter) SetTimeout added in v1.8.20

func (w *DeadlineWriter) SetTimeout(timeout time.Duration)

SetTimeout changes the timeout of each write, and the deadline of the write in progress, to the timeout from now, such as to end a stream to a client which stopped reading sooner, when the server is stopping. It can be called while a write is in progress.

func (*DeadlineWriter) Unwrap added in v1.8.0

func (w *DeadlineWriter) Unwrap() http.ResponseWriter

Unwrap returns the response writer, for a response controller

func (*DeadlineWriter) Write added in v1.8.0

func (w *DeadlineWriter) Write(data []byte) (int, error)

Write writes to the client, by the deadline

type Disposition added in v1.7.15

type Disposition string

Disposition is how a browser presents content: inline, in the browser, or as an attachment, which it saves

const (
	DispositionInline     Disposition = "inline"
	DispositionAttachment Disposition = "attachment"
)

type Err

type Err int

Err turns a HTTP status code into an error

func (Err) Error

func (code Err) Error() string

func (Err) With

func (code Err) With(args ...interface{}) error

func (Err) Withf

func (code Err) Withf(format string, args ...interface{}) error

Withf returns an error wrapping the status code, with a formatted message. As with fmt.Errorf, the format may use %w to wrap errors, so that they can still be matched with errors.Is and errors.As.

type ErrResponse added in v1.6.14

type ErrResponse struct {
	Type   string `json:"object"           jsonschema:"The type of the response, always 'error'"`
	Code   int    `json:"code"             jsonschema:"HTTP status code"`
	Reason string `json:"reason,omitempty" jsonschema:"Human-readable reason phrase"`
	Detail any    `json:"detail,omitempty" jsonschema:"Optional additional detail"`
}

ErrResponse is the JSON error body returned by all error responses. It is also used to generate the OpenAPI response schema.

func (ErrResponse) Error added in v1.6.22

func (err ErrResponse) Error() string

type JSONStream added in v1.6.23

type JSONStream interface {
	Recv() <-chan json.RawMessage
	Send(json.RawMessage) error
}

JSONStream mirrors the client-side streaming interface: Recv yields newline- delimited JSON frames from the request body, and Send writes one JSON frame to the response body followed by a newline and an immediate flush.

type JSONStreamConn added in v1.6.24

type JSONStreamConn interface {
	JSONStream
	Context() context.Context
	Close() error
}

JSONStreamConn is the richer stream connection returned by NewJSONStream. It adds access to the request context and explicit close semantics.

func NewJSONStream added in v1.6.23

func NewJSONStream(w http.ResponseWriter, r *http.Request, headers ...string) (JSONStreamConn, error)

Create a new full-duplex JSON stream with mimetype application/ndjson. Additional header tuples can be provided as a series of key-value pairs.

type JSONStreamHandlerFunc added in v1.6.24

type JSONStreamHandlerFunc func(req *http.Request, stream JSONStream) error

type TextStream

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

TextStream implements a stream of text events

func NewTextStream

func NewTextStream(w http.ResponseWriter, tuples ...string) *TextStream

Create a new text stream with mimetype text/event-stream Additional header tuples can be provided as a series of key-value pairs

func (*TextStream) Close

func (s *TextStream) Close() error

Close the text stream to stop sending ping messages

func (*TextStream) Write

func (s *TextStream) Write(name string, data ...any)

Write a text event to the stream, and one or more optional data objects which are encoded as JSON

Jump to

Keyboard shortcuts

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