Documentation
¶
Index ¶
- Constants
- Variables
- func Accepted(w http.ResponseWriter, data any, opts ...Option) error
- func Blob(w http.ResponseWriter, contentType string, data []byte, opts ...Option) error
- func Created(w http.ResponseWriter, location string, data any, opts ...Option) error
- func Error(w http.ResponseWriter, status int, message string, opts ...Option) error
- func ExcludeFields(data any, fields ...string) any
- func HTML(w http.ResponseWriter, data string, opts ...Option) error
- func JSON(w http.ResponseWriter, data any, opts ...Option) error
- func JSONIndent(w http.ResponseWriter, data any, prefix, indent string, opts ...Option) error
- func JSONP(w http.ResponseWriter, data any, callback string, opts ...Option) error
- func NoContent(w http.ResponseWriter, opts ...Option) error
- func OnlyFields(data any, fields ...string) any
- func Redirect(w http.ResponseWriter, url string, opts ...Option) error
- func ServeFile(w http.ResponseWriter, r *http.Request, filename string, opts ...Option) error
- func ServeFileAsDownload(w http.ResponseWriter, filename string, data []byte, opts ...Option) error
- func Stream(w http.ResponseWriter, reader io.Reader, opts ...Option) error
- func String(w http.ResponseWriter, data string, opts ...Option) error
- func XML(w http.ResponseWriter, data any, opts ...Option) error
- type ErrorResponse
- type JSONEncodeFunc
- type LinkHeader
- type Option
- func AddAccept(value ...string) Option
- func AddAcceptCharset(value ...string) Option
- func AddAcceptEncoding(value ...string) Option
- func AddAcceptLanguage(value ...string) Option
- func AddAccessControlAllowCredentials(enable bool) Option
- func AddAccessControlAllowHeaders(value ...string) Option
- func AddAccessControlAllowMethods(value ...string) Option
- func AddAccessControlAllowOrigin(value ...string) Option
- func AddAccessControlExposeHeaders(value ...string) Option
- func AddAccessControlRequestHeaders(value ...string) Option
- func AddAccessControlRequestMethod(value ...string) Option
- func AddAuthorization(value ...string) Option
- func AddCacheControl(value ...string) Option
- func AddConnection(value ...string) Option
- func AddContentDPR(value float64) Option
- func AddContentDisposition(dispositionType, filename string, useUTF8Encoding ...bool) Option
- func AddContentEncoding(value string) Option
- func AddContentLanguage(value string) Option
- func AddContentLength(length int64) Option
- func AddContentLocation(value string) Option
- func AddContentRange(start, end, total int) Option
- func AddContentSecurityPolicy(value ...string) Option
- func AddContentSecurityPolicyReportOnly(value ...string) Option
- func AddContentType(value string) Option
- func AddDPR(value float64) Option
- func AddDate(date time.Time) Option
- func AddETag(value string) Option
- func AddHost(value string) Option
- func AddIfMatch(value ...string) Option
- func AddIfModifiedSince(t time.Time) Option
- func AddIfNoneMatch(value ...string) Option
- func AddIfRange(value string) Option
- func AddIfUnmodifiedSince(t time.Time) Option
- func AddLastModified(t time.Time) Option
- func AddLink(links ...LinkHeader) Option
- func AddLocation(value string) Option
- func AddOrigin(value ...string) Option
- func AddPragma(value ...string) Option
- func AddProxyAuthenticate(value ...string) Option
- func AddProxyAuthorization(value ...string) Option
- func AddReferer(value string) Option
- func AddReferrerPolicy(value string) Option
- func AddRetryAfter[T int | time.Time | time.Duration](value T) Option
- func AddServer(value string) Option
- func AddStrictTransportSecurity(maxAgeSeconds int, val ...bool) Option
- func AddTransferEncoding(value ...string) Option
- func AddUpgradeInsecureRequests[T int | bool | string](enable T) Option
- func AddUserAgent(value string) Option
- func AddVary(value ...string) Option
- func AddViewportWidth(value int) Option
- func AddWWWAuthenticate(value ...string) Option
- func AddWarning(warnings ...WarningHeader) Option
- func AddWidth(value int) Option
- func AddXContentTypeOptions(value string) Option
- func AddXFrameOptions(value string) Option
- func AddXXSSProtection(value string) Option
- func ApplyJSONEncoder(encodeFunc JSONEncodeFunc) Option
- func AsApplicationForm() Option
- func AsApplicationJSON() Option
- func AsApplicationJSONCharsetUTF8() Option
- func AsApplicationJavaScript() Option
- func AsApplicationJavaScriptCharsetUTF8() Option
- func AsApplicationXML() Option
- func AsApplicationXMLCharsetUTF8() Option
- func AsMultipartForm() Option
- func AsOctetStream() Option
- func AsTextHTML() Option
- func AsTextHTMLCharsetUTF8() Option
- func AsTextJavaScript() Option
- func AsTextJavaScriptCharsetUTF8() Option
- func AsTextPlain() Option
- func AsTextPlainCharsetUTF8() Option
- func AsTextXML() Option
- func AsTextXMLCharsetUTF8() Option
- func SecurityHeaders() Option
- func WithCSP(policy string) Option
- func WithCookie(cookie *http.Cookie) Option
- func WithErrorCode(code int) Option
- func WithErrorSlug(slug string) Option
- func WithHeader(key string, values ...string) Option
- func WithStatus(code int) Option
- func WithStatusAccepted() Option
- func WithStatusAlreadyReported() Option
- func WithStatusBadGateway() Option
- func WithStatusBadRequest() Option
- func WithStatusConflict() Option
- func WithStatusContinue() Option
- func WithStatusCreated() Option
- func WithStatusEarlyHints() Option
- func WithStatusExpectationFailed() Option
- func WithStatusFailedDependency() Option
- func WithStatusForbidden() Option
- func WithStatusFound() Option
- func WithStatusGatewayTimeout() Option
- func WithStatusGone() Option
- func WithStatusHTTPVersionNotSupported() Option
- func WithStatusIMUsed() Option
- func WithStatusInsufficientStorage() Option
- func WithStatusInternalServerError() Option
- func WithStatusLengthRequired() Option
- func WithStatusLocked() Option
- func WithStatusLoopDetected() Option
- func WithStatusMethodNotAllowed() Option
- func WithStatusMisdirectedRequest() Option
- func WithStatusMovedPermanently() Option
- func WithStatusMultiStatus() Option
- func WithStatusMultipleChoices() Option
- func WithStatusNetworkAuthenticationRequired() Option
- func WithStatusNoContent() Option
- func WithStatusNonAuthoritativeInfo() Option
- func WithStatusNotAcceptable() Option
- func WithStatusNotExtended() Option
- func WithStatusNotFound() Option
- func WithStatusNotImplemented() Option
- func WithStatusNotModified() Option
- func WithStatusOK() Option
- func WithStatusPartialContent() Option
- func WithStatusPaymentRequired() Option
- func WithStatusPermanentRedirect() Option
- func WithStatusPreconditionFailed() Option
- func WithStatusPreconditionRequired() Option
- func WithStatusProcessing() Option
- func WithStatusProxyAuthRequired() Option
- func WithStatusRequestEntityTooLarge() Option
- func WithStatusRequestHeaderFieldsTooLarge() Option
- func WithStatusRequestTimeout() Option
- func WithStatusRequestURITooLong() Option
- func WithStatusRequestedRangeNotSatisfiable() Option
- func WithStatusResetContent() Option
- func WithStatusSeeOther() Option
- func WithStatusServiceUnavailable() Option
- func WithStatusSwitchingProtocols() Option
- func WithStatusTeapot() Option
- func WithStatusTemporaryRedirect() Option
- func WithStatusTooEarly() Option
- func WithStatusTooManyRequests() Option
- func WithStatusUnauthorized() Option
- func WithStatusUnavailableForLegalReasons() Option
- func WithStatusUnprocessableEntity() Option
- func WithStatusUnsupportedMediaType() Option
- func WithStatusUpgradeRequired() Option
- func WithStatusUseProxy() Option
- func WithStatusVariantAlsoNegotiates() Option
- func WithStreamJSON() Option
- type R
- type Response
- func (r *Response) Accepted(data any) error
- func (r *Response) AddHeader(key string, value ...string) *Response
- func (r *Response) BindCookie(cookie *http.Cookie) *Response
- func (r *Response) Blob(contentType string, data []byte) error
- func (r *Response) ClearCookies() *Response
- func (r *Response) ClearHeaders() *Response
- func (r *Response) Created(location string, data any) error
- func (r *Response) DelCookie(name string) *Response
- func (r *Response) DelHeader(key string) *Response
- func (r *Response) Error(status int, message string) error
- func (r *Response) ExpiredCookie(name string) *Response
- func (r *Response) GetJSONEncoder() JSONEncodeFunc
- func (r *Response) HTML(html string) error
- func (r *Response) Header() http.Header
- func (r *Response) JSON(data any) error
- func (r *Response) JSONIndent(data any, prefix, indent string) error
- func (r *Response) JSONP(data any, callback string) error
- func (r *Response) NoContent() error
- func (r *Response) Redirect(url string) error
- func (r *Response) ServeFile(req *http.Request, file string) error
- func (r *Response) ServeFileAsDownload(fileName string, data []byte) error
- func (r *Response) SetCookie(cookie *http.Cookie) *Response
- func (r *Response) SetHeader(key string, value ...string) *Response
- func (r *Response) SetJSONEncoder(f JSONEncodeFunc) *Response
- func (r *Response) SetStatus(code int) *Response
- func (r *Response) Status() int
- func (r *Response) Stream(data io.Reader) error
- func (r *Response) String(data string) error
- func (r *Response) XML(data any) error
- type WarningHeader
Examples ¶
Constants ¶
const ( // MIMETextXML is the MIME type for XML documents. MIMETextXML = "text/xml" // MIMETextHTML is the MIME type for HTML documents. MIMETextHTML = "text/html" // MIMETextPlain is the MIME type for plain text. MIMETextPlain = "text/plain" // MIMETextJavaScript is the MIME type for JavaScript code. MIMETextJavaScript = "text/javascript" // MIMEApplicationXML is the MIME type for XML documents, // typically used for APIs or web services. MIMEApplicationXML = "application/xml" // MIMEApplicationJSON is the MIME type for JSON formatted data. MIMEApplicationJSON = "application/json" // MIMEApplicationJavaScript is the MIME type for JavaScript code, // often used for APIs serving JavaScript. MIMEApplicationJavaScript = "application/javascript" // MIMEApplicationForm is the MIME type for URL-encoded form data. MIMEApplicationForm = "application/x-www-form-urlencoded" // MIMEOctetStream is the MIME type for arbitrary binary data. MIMEOctetStream = "application/octet-stream" // MIMEMultipartForm is the MIME type for multipart form data, // used for form submissions that include file uploads. MIMEMultipartForm = "multipart/form-data" // MIMETextXMLCharsetUTF8 is the MIME type for XML documents // using UTF-8 character encoding. MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" // MIMETextHTMLCharsetUTF8 is the MIME type for HTML documents // using UTF-8 character encoding. MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" // MIMETextPlainCharsetUTF8 is the MIME type for plain text // using UTF-8 character encoding. MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" // MIMETextJavaScriptCharsetUTF8 is the MIME type for JavaScript // code using UTF-8 character encoding. MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" // MIMEApplicationXMLCharsetUTF8 is the MIME type for XML documents // using UTF-8 character encoding. MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" // MIMEApplicationJSONCharsetUTF8 is the MIME type for JSON formatted // data using UTF-8 character encoding. MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // MIMEApplicationJavaScriptCharsetUTF8 is the MIME type for JavaScript // code using UTF-8 character encoding. MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
MIME types that are commonly used
const ( // HeaderAuthorization is the HTTP header that represents the credentials // that the client uses to authenticate itself when making a request // to the server. HeaderAuthorization = "Authorization" // HeaderProxyAuthenticate is the HTTP header that represents the // credentials that the proxy can accept for authenticating the client. HeaderProxyAuthenticate = "Proxy-Authenticate" // HeaderProxyAuthorization is the HTTP header that represents the // credentials that the client uses to authenticate itself to a proxy. HeaderProxyAuthorization = "Proxy-Authorization" // HeaderWWWAuthenticate is the HTTP header that represents the method // that should be used to authenticate the client to the server. HeaderWWWAuthenticate = "WWW-Authenticate" // HeaderAge is the HTTP header that represents the time in seconds // the object has been in a proxy cache. HeaderAge = "Age" // HeaderCacheControl is the HTTP header that represents directives // for caching mechanisms in both requests and responses. HeaderCacheControl = "Cache-Control" // HeaderClearSiteData is the HTTP header that tells the browser to // clear various types of cached data (cookies, storage, etc.). HeaderClearSiteData = "Clear-Site-Data" // HeaderExpires is the HTTP header that represents the date/time // after which the response is considered stale. HeaderExpires = "Expires" // HeaderPragma is the HTTP header that represents implementation-specific // directives that might apply to any agent along the request/response // chain. HeaderPragma = "Pragma" // HeaderWarning is the HTTP header that represents general warning // information about possible problems. HeaderWarning = "Warning" // HeaderAcceptCH is the HTTP header that represents the client hints // that the server is willing to accept. HeaderAcceptCH = "Accept-CH" // HeaderAcceptCHLifetime is the HTTP header that represents the lifetime // of the client hints that the server supports. HeaderAcceptCHLifetime = "Accept-CH-Lifetime" // HeaderContentDPR is the HTTP header that represents the device pixel // ratio (DPR) of the client's device. HeaderContentDPR = "Content-DPR" // HeaderDPR is the HTTP header that represents the client's device pixel // ratio for content negotiation. HeaderDPR = "DPR" // HeaderEarlyData is the HTTP header that represents the indication that // the request has been made with early data. HeaderEarlyData = "Early-Data" // HeaderSaveData is the HTTP header that represents the client's // preference for data saving, useful for clients in data-saving mode. HeaderSaveData = "Save-Data" // HeaderViewportWidth is the HTTP header that represents the width of // the viewport in pixels, a hint to help the server select optimized // content for the device. HeaderViewportWidth = "Viewport-Width" // HeaderWidth is the HTTP header that represents the width of the // requested resource, a hint that allows servers to serve different // versions based on the content width. HeaderWidth = "Width" // HeaderETag is the HTTP header that represents the entity tag of the // resource, a mechanism for cache validation and conditional requests. HeaderETag = "ETag" // HeaderIfMatch is the HTTP header that makes the request method // conditional on the resource's ETag matching one of the listed ETags. HeaderIfMatch = "If-Match" // HeaderIfModifiedSince is the HTTP header that makes the request // method conditional on the resource being modified after the // specified date. HeaderIfModifiedSince = "If-Modified-Since" // HeaderIfNoneMatch is the HTTP header that makes the request method // conditional on the resource's ETag not matching any of the listed ETags. HeaderIfNoneMatch = "If-None-Match" // HeaderIfUnmodifiedSince is the HTTP header that makes the request // method conditional on the resource not being modified after the // specified date. HeaderIfUnmodifiedSince = "If-Unmodified-Since" // HeaderLastModified is the HTTP header that represents the date and // time at which the server believes the resource was last modified. HeaderLastModified = "Last-Modified" // HeaderVary is the HTTP header that indicates the set of request-header // fields that fully determines the response sent by the server. HeaderVary = "Vary" // HeaderConnection is the HTTP header that controls whether the network // connection stays open after the current transaction finishes. HeaderConnection = "Connection" // HeaderKeepAlive is the HTTP header that specifies directives for // managing the persistence of the connection. HeaderKeepAlive = "Keep-Alive" // HeaderAccept is the HTTP header that specifies the media types which // are acceptable for the response. HeaderAccept = "Accept" // HeaderAcceptCharset is the HTTP header that specifies the character // sets that are acceptable for the response. HeaderAcceptCharset = "Accept-Charset" // HeaderAcceptEncoding is the HTTP header that specifies the content // encodings that are acceptable in the response. HeaderAcceptEncoding = "Accept-Encoding" // HeaderAcceptLanguage is the HTTP header that specifies the natural // languages that are preferred as a response to the request. HeaderAcceptLanguage = "Accept-Language" // HeaderCookie is the HTTP header that contains stored HTTP cookies // previously sent by the server with the Set-Cookie header. HeaderCookie = "Cookie" // HeaderExpect is the HTTP header that indicates that particular // server behaviors are required by the client. HeaderExpect = "Expect" // HeaderMaxForwards is the HTTP header that represents the maximum // number of times that the request can be forwarded through proxies // or gateways. HeaderMaxForwards = "Max-Forwards" // HeaderSetCookie is the HTTP header that represents the instruction // sent by the server to the client to store a cookie. HeaderSetCookie = "Set-Cookie" // HeaderAccessControlAllowCredentials is the HTTP header that indicates // whether the response to the request can be exposed when the credentials // flag is true. HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" // HeaderAccessControlAllowHeaders is the HTTP header that specifies // the headers that can be used during the actual request. HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" // HeaderAccessControlAllowMethods is the HTTP header that specifies // the methods allowed when accessing the resource in response to // a preflight request. HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" // HeaderAccessControlAllowOrigin is the HTTP header that specifies // the origins that are allowed to access the resource. HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" // HeaderAccessControlExposeHeaders is the HTTP header that lets // a server whitelist headers that browsers are allowed to access. HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" // HeaderAccessControlMaxAge is the HTTP header that indicates how // long the results of a preflight request can be cached. HeaderAccessControlMaxAge = "Access-Control-Max-Age" // HeaderAccessControlRequestHeaders is the HTTP header used in preflight // requests to indicate which HTTP headers can be used during the actual // request. HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" // HeaderAccessControlRequestMethod is the HTTP header used in preflight // requests to indicate which HTTP method can be used during the actual // request. HeaderAccessControlRequestMethod = "Access-Control-Request-Method" // HeaderOrigin is the HTTP header that indicates the origin of the // request or the page making the request. HeaderOrigin = "Origin" // HeaderTimingAllowOrigin is the HTTP header that specifies which // origins are allowed to include timing resources in performance data. HeaderTimingAllowOrigin = "Timing-Allow-Origin" // HeaderXPermittedCrossDomainPolicies is the HTTP header that specifies // the policy that on-site or cross-site policy files can be used to grant // cross-domain loading of content. HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" // HeaderDNT is the HTTP header that represents the "Do Not Track" // request header, indicating the user's tracking preference. HeaderDNT = "DNT" // HeaderTk is the HTTP header that represents the tracking status sent // in response to a DNT request. HeaderTk = "Tk" // HeaderContentDisposition is the HTTP header that represents directives // for content disposition, such as inline or attachment. HeaderContentDisposition = "Content-Disposition" // HeaderContentEncoding is the HTTP header that represents the encoding // transformations that have been applied to the content. HeaderContentEncoding = "Content-Encoding" // HeaderContentLanguage is the HTTP header that represents the natural // language(s) of the intended audience for the content. HeaderContentLanguage = "Content-Language" // HeaderContentLength is the HTTP header that represents the size of the // entity-body in bytes. HeaderContentLength = "Content-Length" // HeaderContentLocation is the HTTP header that represents an alternate // location for the returned content. HeaderContentLocation = "Content-Location" // HeaderContentType is the HTTP header that represents the media type // of the content. HeaderContentType = "Content-Type" // HeaderForwarded is the HTTP header that represents the details of // the forwarding mechanism, including the originating IP. HeaderForwarded = "Forwarded" // HeaderVia is the HTTP header that represents intermediate protocols // and recipients between the user agent and the server on requests, // and between the origin server and the client on responses. HeaderVia = "Via" // HeaderXForwardedFor is the HTTP header that represents the originating // IP addresses of a client connecting to a web server through an HTTP // proxy or a load balancer. HeaderXForwardedFor = "X-Forwarded-For" // HeaderXForwardedHost is the HTTP header that represents the original // host requested by the client in the Host HTTP request header. HeaderXForwardedHost = "X-Forwarded-Host" // HeaderXForwardedProto is the HTTP header that represents the protocol // (HTTP or HTTPS) that a client used to connect to your proxy or load // balancer. HeaderXForwardedProto = "X-Forwarded-Proto" // HeaderXForwardedProtocol is similar to X-Forwarded-Proto, and it // represents the protocol used by the client. HeaderXForwardedProtocol = "X-Forwarded-Protocol" // HeaderXForwardedSSL is the HTTP header that represents the usage of // SSL (HTTPS) by the client. HeaderXForwardedSSL = "X-Forwarded-Ssl" // HeaderXUrlScheme is the HTTP header that represents the scheme // (HTTP/HTTPS) part of the URL requested by the client. HeaderXUrlScheme = "X-Url-Scheme" // HeaderLocation is the HTTP header that represents the URL to // redirect a page to. HeaderLocation = "Location" // HeaderFrom is the HTTP header that represents the email address // of the user making the request. HeaderFrom = "From" // HeaderHost is the HTTP header that represents the domain name of // the server (for virtual hosting), and optionally the TCP port number // on which the server is listening. HeaderHost = "Host" // HeaderReferer is the HTTP header that represents the address of // the previous web page from which a link to the currently requested // page was followed. HeaderReferer = "Referer" // HeaderReferrerPolicy is the HTTP header that represents the policy // governing which referrer information sent in the Referer header should // be included with requests made. HeaderReferrerPolicy = "Referrer-Policy" // HeaderUserAgent is the HTTP header that represents the string // identifying the user agent originating the request. HeaderUserAgent = "User-Agent" // HeaderAllow is the HTTP header that represents the list of HTTP // request methods supported by a resource. HeaderAllow = "Allow" // HeaderServer is the HTTP header that represents the web server // software being used on the responding server. HeaderServer = "Server" // HeaderAcceptRanges is the HTTP header that represents the range // of bytes that the server accepts in the Range header of a request. HeaderAcceptRanges = "Accept-Ranges" // HeaderContentRange is the HTTP header that represents the part of // a document that the server is returning in a partial request response. HeaderContentRange = "Content-Range" // HeaderIfRange is the HTTP header that represents a condition for // sending a partial copy of a resource only if a previous copy has // not been modified. HeaderIfRange = "If-Range" // HeaderRange is the HTTP header that represents the specific part // of a document requested by a client. HeaderRange = "Range" // HeaderContentSecurityPolicy is the HTTP header that represents the // policy that specifies valid sources for content on a webpage. HeaderContentSecurityPolicy = "Content-Security-Policy" // HeaderContentSecurityPolicyReportOnly is the HTTP header that represents // the policy that specifies valid sources for content on a webpage but is // reported only. HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" // HeaderCrossOriginResourcePolicy is the HTTP header that represents the // policy that allows a server to specify the origins that are allowed to // load its resources. HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" // HeaderExpectCT is the HTTP header that represents the policy that allows // sites to opt in to reporting and/or enforcement of Certificate // Transparency requirements. HeaderExpectCT = "Expect-CT" // HeaderPermissionsPolicy is the HTTP header that represents the // permissions policy for a web page, specifying which features are // allowed to be used by the page. HeaderPermissionsPolicy = "Permissions-Policy" // HeaderPublicKeyPins is the HTTP header that represents the Public // Key Pinning Extension for HTTP, associating a specific cryptographic // public key with a web server to decrease the risk of MITM attacks with // forged certificates. HeaderPublicKeyPins = "Public-Key-Pins" // HeaderPublicKeyPinsReportOnly is the HTTP header that represents the // Public Key Pinning Extension for HTTP for report-only mode, which // reports pin validation failures without enforcing them. HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" // HeaderStrictTransportSecurity is the HTTP header that represents the // policy that enforces secure (HTTPS) connections to the server. HeaderStrictTransportSecurity = "Strict-Transport-Security" // HeaderUpgradeInsecureRequests is the HTTP header that represents the // request that the server upgrades the connection to HTTPS. HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" // HeaderXContentTypeOptions is the HTTP header that represents the // directive for the browser to disable MIME type sniffing and strictly // follow the declared content type. HeaderXContentTypeOptions = "X-Content-Type-Options" // HeaderXDownloadOptions is the HTTP header that represents the directive // for Internet Explorer 8+ to not open downloads directly in the browser. HeaderXDownloadOptions = "X-Download-Options" // HeaderXFrameOptions is the HTTP header that represents the directive // that specifies whether a browser should be allowed to render a page // in a <frame>, <iframe>, <embed>, or <object>. HeaderXFrameOptions = "X-Frame-Options" // HeaderXPoweredBy is the HTTP header that represents information // about the technology supporting the web server (often removed for // security reasons). HeaderXPoweredBy = "X-Powered-By" // HeaderXXSSProtection is the HTTP header that represents the directive // for cross-site scripting filter built into most modern web browsers. HeaderXXSSProtection = "X-XSS-Protection" // HeaderLastEventID is the HTTP header that represents the ID of the // last event in an EventSource / Server-Sent Events connection, allowing // resuming of event streams after a disconnection. HeaderLastEventID = "Last-Event-ID" // HeaderNEL is the HTTP header that represents the Network Error Logging // policy, which allows a server to collect network error reports from // user agents. HeaderNEL = "NEL" // HeaderPingFrom is the HTTP header that represents the URL of the Web // page that initiated a ping request during hyperlink auditing. HeaderPingFrom = "Ping-From" // HeaderPingTo is the HTTP header that represents the URL to which a ping // request during hyperlink auditing is sent. HeaderPingTo = "Ping-To" // HeaderReportTo is the HTTP header that represents the endpoint // groups for the Reporting API, allowing the browser to report errors // to the server. HeaderReportTo = "Report-To" // HeaderTE is the HTTP header that represents the transfer encodings // the user agent is willing to accept: chunked, compress, deflate, gzip, // identity. HeaderTE = "TE" // HeaderTrailer is the HTTP header that represents the header fields // present in the trailer of a message encoded with chunked transfer coding. HeaderTrailer = "Trailer" // HeaderTransferEncoding is the HTTP header that represents the form of // encoding used to safely transfer the payload body to the user. HeaderTransferEncoding = "Transfer-Encoding" // HeaderSecWebSocketAccept is the HTTP header that represents the // server's acceptance of a WebSocket handshake request to establish // a WebSocket connection. HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" // HeaderSecWebSocketExtensions is the HTTP header that represents the // accepted extensions for a WebSocket connection. HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" // HeaderSecWebSocketKey is the HTTP header that represents the encoded // key for the server to accept the WebSocket connection. HeaderSecWebSocketKey = "Sec-WebSocket-Key" // HeaderSecWebSocketProtocol is the HTTP header that represents the // agreed-upon protocol during a WebSocket connection handshake. HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" // HeaderSecWebSocketVersion is the HTTP header that represents // the WebSocket protocol version being used by the client. HeaderSecWebSocketVersion = "Sec-WebSocket-Version" // HeaderAcceptPatch is the HTTP header that represents the patch // document formats accepted by the server. HeaderAcceptPatch = "Accept-Patch" // HeaderAcceptPushPolicy is the HTTP header that represents the // server's preferences for HTTP/2 server push. HeaderAcceptPushPolicy = "Accept-Push-Policy" // HeaderAcceptSignature is the HTTP header that represents the // client's support for the HTTP Signatures. HeaderAcceptSignature = "Accept-Signature" // HeaderAltSvc is the HTTP header that represents an alternative // service for accessing a resource. HeaderAltSvc = "Alt-Svc" // HeaderDate is the HTTP header that represents the date and time // at which the message was originated. HeaderDate = "Date" // HeaderIndex is the HTTP header that represents index resources // for a collection of resources. HeaderIndex = "Index" // HeaderLargeAllocation is the HTTP header that hints to the browser // that a large allocation will be made. HeaderLargeAllocation = "Large-Allocation" // HeaderLink is the HTTP header that represents relationships between // the current document and an external resource. HeaderLink = "Link" // HeaderPushPolicy is the HTTP header that represents the server's // policy for HTTP/2 server push. HeaderPushPolicy = "Push-Policy" // HeaderRetryAfter is the HTTP header that represents the amount of // time the client should wait before making a follow-up request. HeaderRetryAfter = "Retry-After" // HeaderServerTiming is the HTTP header that represents the server // timing for performance tracking. HeaderServerTiming = "Server-Timing" // HeaderSignature is the HTTP header that represents the digital // signature for the message content for verification. HeaderSignature = "Signature" // HeaderSignedHeaders is the HTTP header that represents the list // of headers that are included in the digital signature. HeaderSignedHeaders = "Signed-Headers" // HeaderSourceMap is the HTTP header that provides a link to a source // map for debugging purposes. HeaderSourceMap = "SourceMap" // HeaderUpgrade is the HTTP header that requests the client to switch // to a different protocol. HeaderUpgrade = "Upgrade" // HeaderXDNSPrefetchControl is the HTTP header that controls DNS // prefetching, allowing browsers to resolve domain names before // resources are requested. HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" // HeaderXPingback is the HTTP header that specifies the pingback // URL for the resource. HeaderXPingback = "X-Pingback" // HeaderXRequestID is the HTTP header that provides a unique identifier // for the request, facilitating tracing and debugging. HeaderXRequestID = "X-Request-ID" // HeaderXRequestedWith is the HTTP header that identifies the request // as being made with a particular technology, often used to identify // Ajax requests. HeaderXRequestedWith = "X-Requested-With" // HeaderXRobotsTag is the HTTP header that provides directives to search // engines for indexing and serving the content. HeaderXRobotsTag = "X-Robots-Tag" // HeaderXUACompatible is the HTTP header that advises the web browser // to use a specific rendering engine (e.g., IE=edge). HeaderXUACompatible = "X-UA-Compatible" // HeaderAccessControlAllowPrivateNetwork is the HTTP header that grants // web applications on the public internet access to resources on the // user’s private network. HeaderAccessControlAllowPrivateNetwork = "Access-Control-Allow-Private-Network" // HeaderAccessControlRequestPrivateNetwork is the HTTP header used in // preflight requests to indicate access to the user’s private network // is requested by the web application. HeaderAccessControlRequestPrivateNetwork = "Access-Control-Request-Private-Network" )
HTTP Headers were copied from net/http.
const ( // StatusUndefined is a special status code that indicates that the status // code has not been set yet. StatusUndefined = 0 // StatusContinue indicates that the initial part of a request has been // received and has not yet been rejected by the server. // The client SHOULD continue sending the remainder of the request or, // if the request has already been completed, ignore this response. // RFC 9110, Section 15.2.1 StatusContinue = http.StatusContinue // 100 // StatusSwitchingProtocols indicates that the server understands // and is willing to comply with the client's request, via the // Upgrade header field, for a change in the application protocol // being used on this connection. // RFC 9110, Section 15.2.2 StatusSwitchingProtocols = http.StatusSwitchingProtocols // 101 // StatusProcessing is used to inform the client that the server has // accepted the complete request but has not yet completed it. // This status code SHOULD only be sent when the server has a reasonable // expectation that the request will take significant time to complete. // RFC 2518, Section 10.1 (WebDAV) StatusProcessing = http.StatusProcessing // 102 // StatusEarlyHints is primarily intended to be used with the Link header // to allow the user agent to start preloading resources while the server // prepares a response. // RFC 8297 StatusEarlyHints = http.StatusEarlyHints // 103 // StatusOK indicates that the request has succeeded. // RFC 9110, Section 15.3.1 StatusOK = http.StatusOK // 200 // StatusCreated indicates that the request has been fulfilled and has // resulted in one or more new resources being created. // RFC 9110, Section 15.3.2 StatusCreated = http.StatusCreated // 201 // StatusAccepted indicates that the request has been accepted for // processing, but the processing has not been completed. // RFC 9110, Section 15.3.3 StatusAccepted = http.StatusAccepted // 202 // StatusNonAuthoritativeInfo indicates that the request was // successful but the enclosed payload has been modified from that of // the origin server's 200 (OK) response by a transforming proxy. // RFC 9110, Section 15.3.4 StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo // 203 // StatusNoContent indicates that the server has successfully fulfilled // the request and that there is no additional content to send in the // response payload body. // RFC 9110, Section 15.3.5 StatusNoContent = http.StatusNoContent // 204 // StatusResetContent indicates that the server has fulfilled the request // and desires that the user agent reset the "document view", which caused // the request to be sent, to its original state as received from the // origin server. // RFC 9110, Section 15.3.6 StatusResetContent = http.StatusResetContent // 205 // StatusPartialContent indicates that the server is successfully // fulfilling a range request for the target resource by transferring // one or more parts of the selected representation that correspond to // the satisfiable ranges found in the request's Range header field. // RFC 9110, Section 15.3.7 StatusPartialContent = http.StatusPartialContent // 206 // StatusMultiStatus provides status for multiple independent // operations (see WebDAV). // RFC 4918, Section 11.1 StatusMultiStatus = http.StatusMultiStatus // 207 // StatusAlreadyReported is used inside a DAV: propstat response element // to avoid repeatedly enumerating the internal members of multiple // bindings to the same collection. // RFC 5842, Section 7.1 StatusAlreadyReported = http.StatusAlreadyReported // 208 // StatusIMUsed indicates that the server has fulfilled a GET request // for the resource, and the response is a representation of the result // of one or more instance-manipulations applied to the current instance. // RFC 3229, Section 10.4.1 StatusIMUsed = http.StatusIMUsed // 226 // StatusMultipleChoices indicates that the target resource has more than // one representation, each with its own more specific identifier, and // information about the alternatives is being provided so that the user // (or user agent) can select a preferred representation by redirecting // its request to one or more of those identifiers. // RFC 9110, Section 15.4.1 StatusMultipleChoices = http.StatusMultipleChoices // 300 // StatusMovedPermanently indicates that the target resource has been // assigned a new permanent URI and any future references to this resource // ought to use one of the enclosed URIs. // RFC 9110, Section 15.4.2 StatusMovedPermanently = http.StatusMovedPermanently // 301 // StatusFound indicates that the target resource resides temporarily // under a different URI. // RFC 9110, Section 15.4.3 StatusFound = http.StatusFound // 302 // StatusSeeOther indicates that the server is redirecting the user agent // to a different resource, as indicated by a URI in the Location header // field, which is intended to provide an indirect response to the original // request. // RFC 9110, Section 15.4.4 StatusSeeOther = http.StatusSeeOther // 303 // StatusNotModified indicates that a conditional GET request has been // received and would have resulted in a 200 OK response if it were not // for the fact that the condition evaluated to false. // RFC 9110, Section 15.4.5 StatusNotModified = http.StatusNotModified // 304 // StatusUseProxy is deprecated due to security concerns regarding in-band // configuration of a proxy. // RFC 9110, Section 15.4.6 StatusUseProxy = http.StatusUseProxy // 305 // StatusSwitchProxy was defined in a previous version of the HTTP // specification to indicate that a proxy should switch protocols. // RFC 9110 does not define StatusSwitchProxy and this code // is no longer in use. StatusSwitchProxy = 306 // no longer used // StatusTemporaryRedirect indicates that the target resource resides // temporarily under a different URI and the user agent MUST NOT change // the request method if it performs an automatic redirection to that URI. // RFC 9110, Section 15.4.8 StatusTemporaryRedirect = http.StatusTemporaryRedirect // 307 // StatusPermanentRedirect indicates that the target resource has been // assigned a new permanent URI and any future references to this resource // ought to use one of the enclosed URIs. // RFC 9110, Section 15.4.9 StatusPermanentRedirect = http.StatusPermanentRedirect // 308 // StatusBadRequest indicates that the server cannot or will not process // the request due to something that is perceived to be a client error // (e.g., malformed request syntax, invalid request message framing, or // deceptive request routing). // RFC 9110, Section 15.5.1 StatusBadRequest = http.StatusBadRequest // 400 // because it lacks valid authentication credentials for the target // resource. // RFC 9110, Section 15.5.2 StatusUnauthorized = http.StatusUnauthorized // 401 // StatusPaymentRequired is reserved for future use. // RFC 9110, Section 15.5.3 StatusPaymentRequired = http.StatusPaymentRequired // 402 // StatusForbidden indicates that the server understood the request but // refuses to authorize it. // RFC 9110, Section 15.5.4 StatusForbidden = http.StatusForbidden // 403 // StatusNotFound indicates that the origin server did not find a current // representation for the target resource or is not willing to disclose // that one exists. // RFC 9110, Section 15.5.5 StatusNotFound = http.StatusNotFound // 404 // StatusMethodNotAllowed indicates that the method specified in the // request-line is known by the origin server but not supported by // the target resource. // RFC 9110, Section 15.5.6 StatusMethodNotAllowed = http.StatusMethodNotAllowed // 405 // StatusNotAcceptable indicates that the target resource does not have // a current representation that would be acceptable to the user agent, // according to the proactive negotiation header fields received in the // request, and the server is unwilling to supply a default representation. // RFC 9110, Section 15.5.7 StatusNotAcceptable = http.StatusNotAcceptable // 406 // StatusProxyAuthRequired is similar to 401 Unauthorized, but it indicates // that the client needs to authenticate itself in order to use a proxy. // RFC 9110, Section 15.5.8 StatusProxyAuthRequired = http.StatusProxyAuthRequired // 407 // StatusRequestTimeout indicates that the server did not receive // a complete request message within the time that it was prepared to wait. // RFC 9110, Section 15.5.9 StatusRequestTimeout = http.StatusRequestTimeout // 408 // StatusConflict indicates that the request could not be completed due // to a conflict with the current state of the target resource. // RFC 9110, Section 15.5.10 StatusConflict = http.StatusConflict // 409 // StatusGone indicates that access to the target resource is no longer // available at the origin server and that this condition is likely // to be permanent. // RFC 9110, Section 15.5.11 StatusGone = http.StatusGone // 410 // StatusLengthRequired indicates that the server refuses to accept // the request without a defined Content-Length. // RFC 9110, Section 15.5.12 StatusLengthRequired = http.StatusLengthRequired // 411 // StatusPreconditionFailed indicates that one or more conditions // given in the request header fields evaluated to false when tested // on the server. // RFC 9110, Section 15.5.13 StatusPreconditionFailed = http.StatusPreconditionFailed // 412 // StatusRequestEntityTooLarge is deprecated in favor of // StatusPayloadTooLarge. // The server is refusing to process a request because the request // payload is larger than the server is willing or able to process. // RFC 9110, Section 15.5.14 StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge // 413 // StatusRequestURITooLong indicates that the server is refusing // to service the request because the request-target is longer // than the server is willing to interpret. // RFC 9110, Section 15.5.15 StatusRequestURITooLong = http.StatusRequestURITooLong // 414 // StatusUnsupportedMediaType indicates that the origin server is // refusing to service the request because the payload is in a format // not supported by this method on the target resource. // RFC 9110, Section 15.5.16 StatusUnsupportedMediaType = http.StatusUnsupportedMediaType // 415 // StatusRequestedRangeNotSatisfiable indicates that none of the // ranges in the request's Range header field overlap the current // extent of the selected resource or that the set of ranges requested // has been rejected due to invalid ranges or an excessive request of // small or overlapping ranges. // RFC 9110, Section 15.5.17 StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable // 416 // StatusExpectationFailed indicates that the expectation given in the // request's Expect header field could not be met by at least one of // the inbound servers. // RFC 9110, Section 15.5.18 StatusExpectationFailed = http.StatusExpectationFailed // 417 // StatusTeapot is an April Fools' joke from RFC 2324, Hyper Text Coffee // Pot Control Protocol. It's not expected to be implemented by actual // HTTP servers. // RFC 2324, Section 2.3.2 StatusTeapot = http.StatusTeapot // 418 // StatusMisdirectedRequest indicates that the request was directed at // a server that is not able to produce a response. This can be sent by // a server that is not configured to produce responses for the combination // of scheme and authority that are included in the request URI. // RFC 9110, Section 15.5.20 StatusMisdirectedRequest = http.StatusMisdirectedRequest // 421 // StatusUnprocessableEntity indicates that the server understands the // content type of the request entity, and the syntax of the request entity // is correct, but it was unable to process the contained instructions. // RFC 4918, Section 11.2 (WebDAV) StatusUnprocessableEntity = http.StatusUnprocessableEntity // 422 // StatusLocked indicates that the source or destination resource of a // method is locked. // RFC 4918, Section 11.3 (WebDAV) StatusLocked = http.StatusLocked // 423 // StatusFailedDependency indicates that the method could not be performed // on the resource because the requested action depended on another action // and that action failed. // RFC 4918, Section 11.4 (WebDAV) StatusFailedDependency = http.StatusFailedDependency // 424 // StatusTooEarly indicates that the server is unwilling to risk processing // a request that might be replayed. // RFC 8470, Section 5.2 StatusTooEarly = http.StatusTooEarly // 425 // StatusUpgradeRequired indicates that the server refuses to perform the // request using the current protocol but might be willing to do so after // the client upgrades to a different protocol. // RFC 9110, Section 15.5.22 StatusUpgradeRequired = http.StatusUpgradeRequired // 426 // StatusPreconditionRequired indicates that the origin server requires // the request to be conditional. // RFC 6585, Section 3 StatusPreconditionRequired = http.StatusPreconditionRequired // 428 // StatusTooManyRequests indicates the user has sent too many requests // in a given amount of time ("rate limiting"). // RFC 6585, Section 4 StatusTooManyRequests = http.StatusTooManyRequests // 429 // StatusRequestHeaderFieldsTooLarge indicates that the server is unwilling // to process the request because its header fields are too large. // The request MAY be resubmitted after reducing the size of the request // header fields. // RFC 6585, Section 5 StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge // 431 // access to the resource as a consequence of a legal demand. // RFC 7725, Section 3 StatusUnavailableForLegalReasons = http.StatusUnavailableForLegalReasons // 451 // StatusInternalServerError indicates that the server encountered an // unexpected condition that prevented it from fulfilling the request. // RFC 9110, Section 15.6.1 StatusInternalServerError = http.StatusInternalServerError // 500 // StatusNotImplemented indicates that the server does not support the // functionality required to fulfill the request. // RFC 9110, Section 15.6.2 StatusNotImplemented = http.StatusNotImplemented // 501 // StatusBadGateway indicates that the server, while acting as a gateway // or proxy, received an invalid response from an inbound server it // accessed while attempting to fulfill the request. // RFC 9110, Section 15.6.3 StatusBadGateway = http.StatusBadGateway // 502 // unable to handle the request due to a temporary overload or scheduled // maintenance, which will likely be alleviated after some delay. // RFC 9110, Section 15.6.4 StatusServiceUnavailable = http.StatusServiceUnavailable // 503 // StatusGatewayTimeout indicates that the server, while acting as // a gateway or proxy, did not receive a timely response from an // upstream server it needed to access in order to complete the request. // RFC 9110, Section 15.6.5 StatusGatewayTimeout = http.StatusGatewayTimeout // 504 // StatusHTTPVersionNotSupported indicates that the server does not // support, or refuses to support, the major version of HTTP // that was used in the request message. // RFC 9110, Section 15.6.6 StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported // 505 // StatusVariantAlsoNegotiates indicates that the server has an internal // configuration error: the chosen variant resource is configured to // engage in transparent content negotiation itself, and is therefore // not a proper end point in the negotiation process. // RFC 2295, Section 8.1 StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates // 506 // StatusInsufficientStorage indicates that the server is unable to store // the representation needed to complete the request. // RFC 4918, Section 11.5 (WebDAV) StatusInsufficientStorage = http.StatusInsufficientStorage // 507 // StatusLoopDetected indicates that the server detected an infinite loop // while processing the request (sent instead of 208 Already Reported). // RFC 5842, Section 7.2 (WebDAV Binding Extensions) StatusLoopDetected = http.StatusLoopDetected // 508 // StatusNotExtended further extensions to the request are required for // the server to fulfill it. // RFC 2774, Section 7 StatusNotExtended = http.StatusNotExtended // 510 // StatusNetworkAuthenticationRequired indicates that the client needs // to authenticate to gain network access. // RFC 6585, Section 6 StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired // 511 )
HTTP status codes.
Variables ¶
var ErrInvalidJSONPCallback = errors.New("invalid JSONP callback name")
ErrInvalidJSONPCallback is returned by JSONP when the supplied callback name fails validation. It can be matched with errors.Is to distinguish a rejected (potentially malicious) callback from an encoding or write error.
Functions ¶
func Accepted ¶
func Accepted(w http.ResponseWriter, data any, opts ...Option) error
Accepted sends a 202 Accepted response with an optional JSON body.
It is the idiomatic helper for endpoints that accept a request for asynchronous processing: it sets the status to 202 and optionally encodes a tracking representation (e.g. a job handle) as JSON. A nil body sends only the status.
Parameters:
- w: The http.ResponseWriter to which the response will be written.
- data: The payload to encode as JSON (e.g. a job descriptor), or nil.
- opts...: Optional configurations applied to the response.
Returns:
- An error if encoding or writing the response fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
job := enqueue(r)
if err := resp.Accepted(w, resp.R{"job_id": job.ID}); err != nil {
// Handle error...
}
}
func Blob ¶
Blob sends raw bytes with an explicit content type to the client.
It is the in-memory counterpart to ServeFile for arbitrary binary content (PDFs, images, generated documents) that should be displayed rather than downloaded. Content-Length is set automatically; if contentType is empty, "application/octet-stream" is used.
Parameters:
- w: The http.ResponseWriter to which the bytes will be written.
- contentType: The MIME type for the data (e.g. resp.MIMEApplicationPDF). If empty, application/octet-stream is used.
- data: The raw bytes to send as the response body.
- opts...: Optional configurations applied to the response.
Returns:
- An error if writing the response fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
pdf := renderInvoice()
if err := resp.Blob(w, "application/pdf", pdf); err != nil {
// Handle error...
}
}
func Created ¶
Created sends a 201 Created response with an optional Location header and an optional JSON body.
This is the idiomatic helper for REST endpoints that create a resource: it sets the status to 201, points Location at the new resource and encodes the representation as JSON. A nil body sends only the status and headers.
Parameters:
- w: The http.ResponseWriter to which the response will be written.
- location: The URL of the newly created resource (Location header). Omitted from the header when empty.
- data: The created resource to encode as JSON, or nil for no body.
- opts...: Optional configurations applied to the response.
Returns:
- An error if encoding or writing the response fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
user := createUser(r)
if err := resp.Created(w, "/users/"+user.ID, user); err != nil {
// Handle error...
}
}
Example ¶
ExampleCreated returns 201 Created with a Location header and a JSON body — the idiomatic response after creating a REST resource.
package main
import (
"fmt"
"net/http/httptest"
"github.com/goloop/resp/v2"
)
func main() {
w := httptest.NewRecorder()
_ = resp.Created(w, "/users/42", resp.R{"id": 42})
fmt.Println(w.Code)
fmt.Println(w.Header().Get("Location"))
fmt.Print(w.Body.String())
}
Output: 201 /users/42 {"id":42}
func Error ¶
Error sends a JSON error response.
The status argument is the HTTP status code: it is written to the status line and, by default, mirrored into the JSON body's "code" field, so a single call keeps the two consistent. The status argument always wins over a WithStatus option; an out-of-range value falls back to StatusInternalServerError. When message is empty, the canonical text for the status code is used.
To return a distinct application/business code in the body while keeping the HTTP status, add WithErrorCode.
Parameters:
- w: The http.ResponseWriter to which the error response will be written.
- status: The HTTP status code (100-599). Also used as the body code unless overridden with WithErrorCode.
- message: The error message for the response body. If empty, the canonical message for the status code is used.
- opts...: Optional configurations applied to the response.
Returns: - An error if writing the response fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
// HTTP 404, body {"code":404,"message":"Not Found"}.
if err := resp.Error(w, http.StatusNotFound, ""); err != nil {
// Handle error...
}
// HTTP 404, body {"code":1042,"message":"User not found"}.
err := resp.Error(w, http.StatusNotFound, "User not found",
resp.WithErrorCode(1042))
if err != nil {
// Handle error...
}
}
Example ¶
ExampleError shows the v2 error contract: the first argument is the HTTP status (mirrored into the body), and WithErrorCode overrides only the body code with a separate business code.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/goloop/resp/v2"
)
func main() {
w := httptest.NewRecorder()
_ = resp.Error(w, http.StatusNotFound, "User not found", resp.WithErrorCode(1042))
fmt.Println(w.Code)
fmt.Print(w.Body.String())
}
Output: 404 {"code":1042,"message":"User not found"}
func ExcludeFields ¶
ExcludeFields removes the specified fields from the provided data and returns the remaining fields as an `R` map. This function is useful for creating JSON responses without sensitive or unwanted fields from the original data. The operation can be performed on a single object, a slice of objects, an array of objects, or a map. When a slice or an array is provided, the function returns a slice of `R` maps. If the data is not a struct, slice/array of structs, or map with string keys, it returns the original data unchanged.
Parameters:
- data: The input data from which fields will be excluded. It can be a struct, a slice/array of structs, or a map with string keys (`map[string]any`).
- fields: A list of field names to exclude from the resulting map.
Returns:
- An `R` map containing the fields from the input data except the specified fields, a slice of `R` maps if the input data is a slice or an array, or the original input data unchanged if it is not a struct, a map with string keys, or a slice/array of structs.
Example Usage: The following example demonstrates how to use `ExcludeFields` to create a JSON response that excludes specific fields from a user object.
import (
"net/http"
"github.com/goloop/resp/v2"
)
type User struct {
ID int
Email string
Password string
IsActive bool
}
func UserData(w http.ResponseWriter, r *http.Request) {
user := User{
ID: 1,
Email: "user_a@example.com",
Password: "secret",
IsActive: true,
}
data := resp.ExcludeFields(user, "Password")
if err := resp.JSON(w, data); err != nil {
// handle error
}
}
func UserList(w http.ResponseWriter, r *http.Request) {
users := []User{
{
ID: 1,
Email: "user_a@example.com",
Password: "secret",
IsActive: true,
},
{
ID: 2,
Email: "user_b@example.com",
Password: "secret",
IsActive: true,
},
}
data := resp.ExcludeFields(users, "Password")
if err := resp.JSON(w, data); err != nil {
// handle error
}
}
func HTML ¶
func HTML(w http.ResponseWriter, data string, opts ...Option) error
HTML sends an HTML response to the client.
This function simplifies the process of sending HTML content as a response. It's particularly useful for serving web pages or HTML fragments. By default, it sets the Content-Type header to "text/html". This function can be configured with various options to set custom headers, status codes, or other response settings, making it versatile for web development needs.
Parameters:
- w: The http.ResponseWriter to which the HTML content will be written.
- data: The HTML content to be sent as the response body. This should be a valid HTML string.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns:
- An error if there's an issue writing the HTML response. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
template := `
<!DOCTYPE html>
<html>
<head><title>Example Page</title></head>
<body>
<h1>Hello, World!</h1>
<p>This is example page.</p>
</body>
</html>
`
// Send the HTML content as a response.
if err := HTML(w, template, WithStatus(http.StatusOK)); err != nil {
// Handle error
log.Printf("Failed to send HTML response: %v", err)
resp.Error(w, 500, "Failed to send HTML response")
}
}
func JSON ¶
func JSON(w http.ResponseWriter, data any, opts ...Option) error
JSON sends a JSON response to the client.
This function wraps the process of setting up a JSON response by initializing a new Response object with optional configurations and then using it to encode the provided data as JSON. It sets the Content-Type header to "application/json" and writes the encoded JSON data to the client. This function simplifies the process of returning JSON data in your HTTP handlers.
Parameters:
- w: The http.ResponseWriter that the JSON response will be written to.
- data: The data to be encoded as JSON. This can be any Go data structure, including structs and slices.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns: - An error if encoding the JSON fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
data := struct {
Name string `json:"name"`
Age int `json:"age"`
}{
Name: "John Doe",
Age: 30,
}
// // With custom settings.
// // Send a JSON response with HTTP status 200 OK and custom header.
// if err := resp.JSON(w, data, WithStatus(http.StatusOK),
// WithHeader("X-Custom-Header", "value")); err != nil {
// // Handle error...
// }
// With default settings.
if err := resp.JSON(w, data); err != nil {
// Handle error...
}
}
Example ¶
ExampleJSON sends a JSON object using the R shorthand map.
package main
import (
"fmt"
"net/http/httptest"
"github.com/goloop/resp/v2"
)
func main() {
w := httptest.NewRecorder()
_ = resp.JSON(w, resp.R{"message": "hello", "ok": true})
fmt.Print(w.Body.String())
}
Output: {"message":"hello","ok":true}
func JSONIndent ¶
JSONIndent sends an indented (pretty-printed) JSON response to the client.
It behaves like JSON but formats the output with the given prefix and indent (as in json.Encoder.SetIndent), which is convenient for human-readable or debug endpoints. The standard library encoder is always used, so a custom encoder supplied via ApplyJSONEncoder is ignored here.
Parameters:
- w: The http.ResponseWriter that the JSON response will be written to.
- data: The data to be encoded as JSON.
- prefix: The line prefix for each JSON element (usually "").
- indent: The per-level indentation string (e.g. " " or "\t").
- opts...: Optional configurations applied to the response.
Returns:
- An error if encoding the JSON fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
if err := resp.JSONIndent(w, data, "", " "); err != nil {
// Handle error...
}
}
func JSONP ¶
JSONP sends a JSONP (JSON with Padding) response to the client.
This function is particularly useful for serving JSON responses to web pages making requests across domain boundaries, where direct JSON responses might be blocked due to browser same-origin policies. JSONP wraps the JSON data in a callback function specified by the client, enabling cross-domain data communication in JavaScript by bypassing same-origin restrictions.
Parameters:
- w: The http.ResponseWriter to which the JSONP response is written.
- data: The data to be encoded as JSON and wrapped in the callback function. This can be any Go data structure, including structs and slices.
- callback: The name of the callback function to wrap the JSON data. This function name is typically provided by the client in the request query string.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns: - An error if encoding the JSON fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{"hello": "world"}
// Extract callback function name from query parameters.
callback := r.URL.Query().Get("callback")
// Send a JSONP response.
if err := resp.JSONP(w, data, callback); err != nil {
// Handle error...
}
}
func NoContent ¶
func NoContent(w http.ResponseWriter, opts ...Option) error
NoContent sends a 204 No Content response to the client.
This function is useful for endpoints that successfully process a request but do not need to return any data in the response body, such as a successful deletion of a resource or a successful update operation where no confirmation is needed. It sets the status code to 204 No Content by default, but this can be overridden using options to accommodate any additional requirements.
Parameters:
- w: The http.ResponseWriter to which the no content response is written.
- opts...: Optional configurations applied to the response. This can be used to set custom headers or other response settings as needed.
Returns: - An error if there's an issue setting up the response. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
// Perform the deletion operation...
// Respond with no content status to indicate success
if err := resp.NoContent(w); err != nil {
log.Printf("Failed to send no content response: %v", err)
}
}
func OnlyFields ¶
OnlyFields extracts only the specified fields from the provided data and returns them as an `R` map. This function is useful for creating JSON responses with a subset of the original data. The operation can be performed on a single object, a slice of objects, an array of objects, or a map. When a slice or an array is provided, the function returns a slice of `R` maps. If the data is not a struct, slice/array of structs, or map with string keys, it returns the original data unchanged.
Parameters:
- data: The input data from which fields will be extracted. It can be a struct, a slice/array of structs, or a map with string keys (`map[string]any`).
- fields: A list of field names to include in the resulting map.
Returns:
- An `R` map containing only the specified fields from the input data, a slice of `R` maps if the input data is a slice or an array, or the original input data unchanged if it is not a struct, a map with string keys, or a slice/array of structs.
Example Usage: The following example demonstrates how to use `OnlyFields` to create a JSON response that includes only specific fields from a user object.
import (
"net/http"
"github.com/goloop/resp/v2"
)
type User struct {
ID int
Email string
Password string
IsActive bool
}
func UserData(w http.ResponseWriter, r *http.Request) {
user := User{
ID: 1,
Email: "user_a@example.com",
Password: "secret",
IsActive: true,
}
data := resp.OnlyFields(user, "ID", "Email", "IsActive")
if err := resp.JSON(w, data); err != nil {
// handle error
}
}
func UserList(w http.ResponseWriter, r *http.Request) {
users := []User{
{
ID: 1,
Email: "user_a@example.com",
Password: "secret",
IsActive: true,
},
{
ID: 2,
Email: "user_b@example.com",
Password: "secret",
IsActive: true,
},
}
data := resp.OnlyFields(users, "ID", "Email", "IsActive")
if err := resp.JSON(w, data); err != nil {
// handle error
}
}
Example ¶
ExampleOnlyFields keeps only the whitelisted fields of a struct — a typical way to hide a password before serialization.
package main
import (
"encoding/json"
"fmt"
"github.com/goloop/resp/v2"
)
func main() {
type User struct {
ID int
Email string
Password string
}
u := User{ID: 1, Email: "user@example.com", Password: "secret"}
data := resp.OnlyFields(u, "ID", "Email")
out, _ := json.Marshal(data)
fmt.Println(string(out))
}
Output: {"Email":"user@example.com","ID":1}
func Redirect ¶
func Redirect(w http.ResponseWriter, url string, opts ...Option) error
Redirect sends a redirect response to the client, instructing the browser to navigate to a different URL.
This function simplifies sending HTTP redirects by automatically setting the status code to 302 Found, unless otherwise specified in the options. It's useful for handling requests where the resource has been moved or when the request should be redirected to a different endpoint.
Parameters:
- w: The http.ResponseWriter to which the redirect response is written.
- url: The URL to which the client will be redirected.
- opts...: Optional configurations applied to the response. This can include setting a specific status code using WithStatus if a different type of redirect is required (e.g., 301 Moved Permanently).
Returns:
- An error if there's an issue writing the redirect response. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
// Define the URL to redirect to.
newURL := "https://example.com/new-page"
// Redirect the request to the new URL.
if err := Redirect(w, newURL); err != nil {
log.Printf("Failed to redirect: %v", err)
}
}
func ServeFile ¶
ServeFile sends a file response to the client.
This function is designed to simplify the process of serving static files (e.g., images, documents, media files) to the client over HTTP. It leverages http.ServeFile to handle the details of reading and transmitting the file, including setting appropriate headers for caching, content type detection, and handling range requests for efficient media streaming. The function can be configured with various options to set custom headers, status codes, or other response settings before the file is served.
Parameters:
- w: The http.ResponseWriter to which the file will be written.
- r: The *http.Request object that initiated the file request. This is required for handling conditional GET requests and range requests.
- filename: The path to the file that will be served. This must be a valid file path accessible by the server.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns:
- An error if there's an issue serving the file. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
// Assuming there's a query parameter 'file' with the filename.
filename := r.URL.Query().Get("file")
if filename == "" {
resp.Error(w, http.StatusBadRequest, "File not specified")
return
}
// Serve the file with Content-Disposition header for download.
err := resp.ServeFile(w, r, filepath.Join("static", filename),
resp.AddContentDisposition("attachment", filename))
if err != nil {
log.Printf("Failed to serve file: %v", err)
resp.Error(w, 500, "Failed to serve file")
}
}
func ServeFileAsDownload ¶
func ServeFileAsDownload( w http.ResponseWriter, filename string, data []byte, opts ...Option, ) error
ServeFileAsDownload sends a file as a download response to the client.
This function is intended for scenarios where you need to serve dynamically generated content or files stored in memory as downloads, rather than serving files directly from the filesystem. It sets the Content-Disposition header to prompt the browser to treat the response as a file to be downloaded. The function can be configured with various options to set custom headers, status codes, or other response settings before the download is initiated.
Parameters:
- w: The http.ResponseWriter to which the download response will be written.
- filename: The filename to be used in the Content-Disposition header, suggesting the name the browser should use to save the downloaded file.
- data: The byte slice containing the file data to be sent as the download.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns:
- An error if there's an issue writing the download response. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
// Generate or retrieve the file data.
fileData := []byte("Hello, world!")
filename := "greeting.txt"
// Send the file data as a download.
err := ServeFileAsDownload(w, filename, fileData)
if err != nil {
log.Printf("Failed to serve file download: %v", err)
resp.Error(w, 500, "Failed to serve file download")
}
}
func Stream ¶
Stream sends a stream response to the client.
This function facilitates the sending of streaming data, such as file downloads or video streaming, by encapsulating the process of streaming from an io.Reader to the http.ResponseWriter. It can be configured with various options to set headers or status codes before streaming begins. The Content-Type of the response should be set appropriately using options, depending on the type of data being streamed.
Parameters:
- w:The http.ResponseWriter to which the streaming response will be written.
- reader: An io.Reader from which data will be read and streamed to the response. This could be a file, a buffer, or any other data source implementing io.Reader.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings.
Returns:
- An error if there's an issue writing the stream to the response. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("video.mp4")
if err != nil {
resp.Error(w, resp.StatusNotFound, "Not found")
return
}
defer file.Close()
// Stream the file to the response with the correct Content-Type.
err := resp.Stream(w, file, WithHeader("Content-Type", "video/mp4"))
if err != nil {
log.Printf("Failed to stream file: %v", err)
}
}
func String ¶
func String(w http.ResponseWriter, data string, opts ...Option) error
String sends a plain text response to the client.
This function simplifies the process of sending text-based responses, such as HTML or plain text, by encapsulating the creation of a Response object and setting the appropriate Content-Type header. It's particularly useful for endpoints that return non-JSON responses, providing a convenient way to return text data.
Parameters:
- w: The http.ResponseWriter that the text response will be written to.
- data: The string data to be sent as the response body. This can be any text data, including HTML or plain text.
- opts...: Optional configurations applied to the response. These can be used to set custom headers, status codes, or other response settings, including changing the Content-Type from its default ("text/plain").
Returns: - An error if writing the response fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
message := "Hello, World!"
// Send a plain text response with HTTP status 200 OK.
if err := resp.String(w, message); err != nil {
// Handle error...
}
}
func XML ¶
func XML(w http.ResponseWriter, data any, opts ...Option) error
XML sends an XML response to the client.
It mirrors JSON for XML payloads: the Content-Type defaults to "application/xml; charset=utf-8" and the data is encoded with encoding/xml. Like JSON, encoding happens into a buffer first, so a marshalling error is returned before the status line is committed.
Parameters:
- w: The http.ResponseWriter that the XML response will be written to.
- data: The data to be encoded as XML (typically a struct with xml tags).
- opts...: Optional configurations applied to the response.
Returns:
- An error if encoding the XML fails. Otherwise, nil.
Example usage:
func Handler(w http.ResponseWriter, r *http.Request) {
type Note struct {
XMLName xml.Name `xml:"note"`
To string `xml:"to"`
}
if err := resp.XML(w, Note{To: "World"}); err != nil {
// Handle error...
}
}
Types ¶
type ErrorResponse ¶
type ErrorResponse struct {
Code int `json:"code"` // error code
// Error is a machine-readable name for what went wrong, such as
// "rate_limit" or "slug_taken". It is what a client switches on and what
// a translation key is looked up by; a number cannot do either without a
// registry that nobody maintains, and "1042" says nothing in a log or a
// test either.
//
// It is omitted when unset, so a response that does not name one is
// exactly the bytes it was before this field existed. See WithErrorSlug.
Error string `json:"error,omitempty"`
Message string `json:"message"` // error message
}
ErrorResponse represents an error response.
func (*ErrorResponse) Unpack ¶
func (e *ErrorResponse) Unpack() (code int, message string)
Unpack returns the error code and message.
type JSONEncodeFunc ¶
JSONEncodeFunc represents a function that encodes the provided data into JSON and writes it to the provided io.Writer. This allows for custom JSON encoding strategies.
Example Usage:
// Using a custom JSON encoder.
customEncoder := func(w io.Writer, v any) error {
return json.NewEncoder(w).Encode(v)
}
resp.JSON(w, data, resp.ApplyJSONEncoder(customEncoder))
type LinkHeader ¶
LinkHeader represents a Link header.
type Option ¶
Option represents a response option.
func AddAcceptCharset ¶
AddAcceptCharset sets the Accept-Charset header.
func AddAcceptEncoding ¶
AddAcceptEncoding sets the Accept-Encoding header.
func AddAcceptLanguage ¶
AddAcceptLanguage sets the Accept-Language header.
func AddAccessControlAllowCredentials ¶
AddAccessControlAllowCredentials sets the Access-Control-Allow-Credentials header.
func AddAccessControlAllowHeaders ¶
AddAccessControlAllowHeaders sets the Access-Control-Allow-Headers header.
func AddAccessControlAllowMethods ¶
AddAccessControlAllowMethods sets the Access-Control-Allow-Methods header.
func AddAccessControlAllowOrigin ¶
AddAccessControlAllowOrigin sets the Access-Control-Allow-Origin header.
func AddAccessControlExposeHeaders ¶
AddAccessControlExposeHeaders sets the Access-Control-Expose-Headers header.
func AddAccessControlRequestHeaders ¶
AddAccessControlRequestHeaders sets the Access-Control-Request-Headers header.
func AddAccessControlRequestMethod ¶
AddAccessControlRequestMethod sets the Access-Control-Request-Method header.
func AddAuthorization ¶
AddAuthorization sets the Authorization header.
func AddCacheControl ¶
AddCacheControl sets the Cache-Control header.
func AddConnection ¶
AddConnection sets the Connection header.
func AddContentDPR ¶
AddContentDPR sets the Content-DPR header.
func AddContentDisposition ¶
AddContentDisposition sets the Content-Disposition header.
func AddContentEncoding ¶
AddContentEncoding sets the Content-Encoding header.
func AddContentLanguage ¶
AddContentLanguage sets the Content-Language header.
func AddContentLength ¶
AddContentLength sets the Content-Length header.
func AddContentLocation ¶
AddContentLocation sets the Content-Location header.
func AddContentRange ¶
AddContentRange sets the Content-Range header.
func AddContentSecurityPolicy ¶
AddContentSecurityPolicy sets the Content-Security-Policy header.
func AddContentSecurityPolicyReportOnly ¶
AddContentSecurityPolicyReportOnly sets the Content-Security-Policy-Report-Only header.
func AddContentType ¶
AddContentType sets the Content-Type header.
func AddIfModifiedSince ¶
AddIfModifiedSince sets the If-Modified-Since header.
func AddIfNoneMatch ¶
AddIfNoneMatch sets the If-None-Match header.
func AddIfUnmodifiedSince ¶
AddIfUnmodifiedSince sets the If-Unmodified-Since header.
func AddLastModified ¶
AddLastModified sets the Last-Modified header.
func AddProxyAuthenticate ¶
AddProxyAuthenticate sets the Proxy-Authenticate header.
func AddProxyAuthorization ¶
AddProxyAuthorization sets the Proxy-Authorization header.
func AddReferrerPolicy ¶
AddReferrerPolicy sets the Referrer-Policy header.
func AddRetryAfter ¶
AddRetryAfter sets the Retry-After header.
func AddStrictTransportSecurity ¶
AddStrictTransportSecurity sets the Strict-Transport-Security header. The maxAgeSeconds parameter is the number of seconds that the browser should remember that this site is only to be accessed using HTTPS.
If includeSubDomains is true, this rule applies to all of the site's subdomains. If preload is true, the site is included in the HSTS preload list.
The val parameter is optional and can be used to set the includeSubDomains and preload values.
For example:
AddStrictTransportSecurity(31536000) AddStrictTransportSecurity(31536000, true, true) AddStrictTransportSecurity(31536000, false, true) AddStrictTransportSecurity(31536000, true)
func AddTransferEncoding ¶
AddTransferEncoding sets the Transfer-Encoding header.
func AddUpgradeInsecureRequests ¶
AddUpgradeInsecureRequests sets the Upgrade-Insecure-Requests header.
func AddViewportWidth ¶
AddViewportWidth sets the Viewport-Width header.
func AddWWWAuthenticate ¶
AddWWWAuthenticate sets the WWW-Authenticate header.
func AddWarning ¶
func AddWarning(warnings ...WarningHeader) Option
AddWarning sets the Warning header.
func AddXContentTypeOptions ¶
AddXContentTypeOptions sets the X-Content-Type-Options header.
func AddXFrameOptions ¶
AddXFrameOptions sets the X-Frame-Options header.
func AddXXSSProtection ¶
AddXXSSProtection sets the X-XSS-Protection header.
func ApplyJSONEncoder ¶
func ApplyJSONEncoder(encodeFunc JSONEncodeFunc) Option
ApplyJSONEncoder sets the custom JSON encoder function. This allows us to plug in a different JSON encoder or customize encoding.
Example Usage:
customEncoder := func(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(v)
}
response := resp.NewResponse(w, resp.ApplyJSONEncoder(customEncoder))
func AsApplicationForm ¶
func AsApplicationForm() Option
AsApplicationForm sets the Content-Type header to application/x-www-form-urlencoded.
func AsApplicationJSON ¶
func AsApplicationJSON() Option
AsApplicationJSON sets the Content-Type header to application/json.
func AsApplicationJSONCharsetUTF8 ¶
func AsApplicationJSONCharsetUTF8() Option
AsApplicationJSONCharsetUTF8 sets the Content-Type header to application/json; charset=utf-8.
func AsApplicationJavaScript ¶
func AsApplicationJavaScript() Option
AsApplicationJavaScript sets the Content-Type header to application/javascript.
func AsApplicationJavaScriptCharsetUTF8 ¶
func AsApplicationJavaScriptCharsetUTF8() Option
AsApplicationJavaScriptCharsetUTF8 sets the Content-Type header to application/javascript; charset=utf-8.
func AsApplicationXML ¶
func AsApplicationXML() Option
AsApplicationXML sets the Content-Type header to application/xml.
func AsApplicationXMLCharsetUTF8 ¶
func AsApplicationXMLCharsetUTF8() Option
AsApplicationXMLCharsetUTF8 sets the Content-Type header to application/xml; charset=utf-8.
func AsMultipartForm ¶
func AsMultipartForm() Option
AsMultipartForm sets the Content-Type header to multipart/form-data.
func AsOctetStream ¶
func AsOctetStream() Option
AsOctetStream sets the Content-Type header to application/octet-stream.
func AsTextHTMLCharsetUTF8 ¶
func AsTextHTMLCharsetUTF8() Option
AsTextHTMLCharsetUTF8 sets the Content-Type header to text/html; charset=utf-8.
func AsTextJavaScript ¶
func AsTextJavaScript() Option
AsTextJavaScript sets the Content-Type header to text/javascript.
func AsTextJavaScriptCharsetUTF8 ¶
func AsTextJavaScriptCharsetUTF8() Option
AsTextJavaScriptCharsetUTF8 sets the Content-Type header to text/javascript; charset=utf-8.
func AsTextPlain ¶
func AsTextPlain() Option
AsTextPlain sets the Content-Type header to text/plain.
func AsTextPlainCharsetUTF8 ¶
func AsTextPlainCharsetUTF8() Option
AsTextPlainCharsetUTF8 sets the Content-Type header to text/plain; charset=utf-8.
func AsTextXMLCharsetUTF8 ¶
func AsTextXMLCharsetUTF8() Option
AsTextXMLCharsetUTF8 sets the Content-Type header to text/xml; charset=utf-8.
func SecurityHeaders ¶
func SecurityHeaders() Option
SecurityHeaders applies a conservative, broadly-safe set of security response headers:
X-Content-Type-Options: nosniff X-Frame-Options: DENY Referrer-Policy: strict-origin-when-cross-origin
It deliberately does NOT set a Content-Security-Policy: an effective CSP is application-specific and a wrong one silently breaks pages. Add one explicitly with WithCSP when you know the policy your app needs. Any existing values for these three headers are overwritten.
func WithCSP ¶
WithCSP sets the Content-Security-Policy header to the given policy. CSP is kept separate from SecurityHeaders because a useful policy is specific to each application; this option lets you opt in explicitly.
resp.JSON(w, data,
resp.SecurityHeaders(),
resp.WithCSP("default-src 'self'"))
func WithCookie ¶
WithCookie sets the provided cookie in the response.
func WithErrorCode ¶
WithErrorCode overrides only the "code" field of the JSON error body produced by Error, decoupling the application/business code from the HTTP status. Without this option the body code mirrors the HTTP status passed to Error.
resp.Error(w, 404, "User not found", resp.WithErrorCode(1042))
// HTTP 404, body {"code":1042,"message":"User not found"}
func WithErrorSlug ¶ added in v2.3.0
WithErrorSlug adds a machine-readable name to the JSON error body produced by Error, beside the numeric code and the human message:
resp.Error(w, 409, "That name is already in use",
resp.WithErrorSlug("slug_taken"))
// HTTP 409, body {"code":409,"error":"slug_taken","message":"..."}
This is the field a client switches on and a translation key is looked up by. A numeric code cannot serve either purpose without a registry mapping numbers to meanings, and such a registry is exactly the thing that stops being maintained; the number also says nothing in a log line or a failing test, where the slug says everything.
The slug is the application's own vocabulary, so it is not validated - but keep it to a short constant from a fixed set, in the shape of [a-z0-9_]+. It is copied into the response body verbatim, which makes it the wrong place for anything that came from a request.
Without this option the body is unchanged, field for field.
func WithHeader ¶
WithHeader adds the provided header key-value pair to the response.
func WithStatus ¶
WithStatus sets the status code of the response.
Note: Error ignores this option — its first argument is authoritative for the HTTP status. NoContent always responds with 204 regardless.
func WithStatusAccepted ¶
func WithStatusAccepted() Option
WithStatusAccepted sets the status code to 202.
func WithStatusAlreadyReported ¶
func WithStatusAlreadyReported() Option
WithStatusAlreadyReported sets the status code to 208.
func WithStatusBadGateway ¶
func WithStatusBadGateway() Option
WithStatusBadGateway sets the status code to 502.
func WithStatusBadRequest ¶
func WithStatusBadRequest() Option
WithStatusBadRequest sets the status code to 400.
func WithStatusConflict ¶
func WithStatusConflict() Option
WithStatusConflict sets the status code to 409.
func WithStatusContinue ¶
func WithStatusContinue() Option
WithStatusContinue sets the status code to 100.
func WithStatusCreated ¶
func WithStatusCreated() Option
WithStatusCreated sets the status code to 201.
func WithStatusEarlyHints ¶
func WithStatusEarlyHints() Option
WithStatusEarlyHints sets the status code to 103.
func WithStatusExpectationFailed ¶
func WithStatusExpectationFailed() Option
WithStatusExpectationFailed sets the status code to 417.
func WithStatusFailedDependency ¶
func WithStatusFailedDependency() Option
WithStatusFailedDependency sets the status code to 424.
func WithStatusForbidden ¶
func WithStatusForbidden() Option
WithStatusForbidden sets the status code to 403.
func WithStatusGatewayTimeout ¶
func WithStatusGatewayTimeout() Option
WithStatusGatewayTimeout sets the status code to 504.
func WithStatusHTTPVersionNotSupported ¶
func WithStatusHTTPVersionNotSupported() Option
WithStatusHTTPVersionNotSupported sets the status code to 505.
func WithStatusIMUsed ¶
func WithStatusIMUsed() Option
WithStatusIMUsed sets the status code to 226.
func WithStatusInsufficientStorage ¶
func WithStatusInsufficientStorage() Option
WithStatusInsufficientStorage sets the status code to 507.
func WithStatusInternalServerError ¶
func WithStatusInternalServerError() Option
WithStatusInternalServerError sets the status code to 500.
func WithStatusLengthRequired ¶
func WithStatusLengthRequired() Option
WithStatusLengthRequired sets the status code to 411.
func WithStatusLocked ¶
func WithStatusLocked() Option
WithStatusLocked sets the status code to 423.
func WithStatusLoopDetected ¶
func WithStatusLoopDetected() Option
WithStatusLoopDetected sets the status code to 508.
func WithStatusMethodNotAllowed ¶
func WithStatusMethodNotAllowed() Option
WithStatusMethodNotAllowed sets the status code to 405.
func WithStatusMisdirectedRequest ¶
func WithStatusMisdirectedRequest() Option
WithStatusMisdirectedRequest sets the status code to 421.
func WithStatusMovedPermanently ¶
func WithStatusMovedPermanently() Option
WithStatusMovedPermanently sets the status code to 301.
func WithStatusMultiStatus ¶
func WithStatusMultiStatus() Option
WithStatusMultiStatus sets the status code to 207.
func WithStatusMultipleChoices ¶
func WithStatusMultipleChoices() Option
WithStatusMultipleChoices sets the status code to 300.
func WithStatusNetworkAuthenticationRequired ¶
func WithStatusNetworkAuthenticationRequired() Option
WithStatusNetworkAuthenticationRequired sets the status code to 511.
func WithStatusNoContent ¶
func WithStatusNoContent() Option
WithStatusNoContent sets the status code to 204.
func WithStatusNonAuthoritativeInfo ¶
func WithStatusNonAuthoritativeInfo() Option
WithStatusNonAuthoritativeInfo sets the status code to 203.
func WithStatusNotAcceptable ¶
func WithStatusNotAcceptable() Option
WithStatusNotAcceptable sets the status code to 406.
func WithStatusNotExtended ¶
func WithStatusNotExtended() Option
WithStatusNotExtended sets the status code to 510.
func WithStatusNotFound ¶
func WithStatusNotFound() Option
WithStatusNotFound sets the status code to 404.
func WithStatusNotImplemented ¶
func WithStatusNotImplemented() Option
WithStatusNotImplemented sets the status code to 501.
func WithStatusNotModified ¶
func WithStatusNotModified() Option
WithStatusNotModified sets the status code to 304.
func WithStatusPartialContent ¶
func WithStatusPartialContent() Option
WithStatusPartialContent sets the status code to 206.
func WithStatusPaymentRequired ¶
func WithStatusPaymentRequired() Option
WithStatusPaymentRequired sets the status code to 402.
func WithStatusPermanentRedirect ¶
func WithStatusPermanentRedirect() Option
WithStatusPermanentRedirect sets the status code to 308.
func WithStatusPreconditionFailed ¶
func WithStatusPreconditionFailed() Option
WithStatusPreconditionFailed sets the status code to 412.
func WithStatusPreconditionRequired ¶
func WithStatusPreconditionRequired() Option
WithStatusPreconditionRequired sets the status code to 428.
func WithStatusProcessing ¶
func WithStatusProcessing() Option
WithStatusProcessing sets the status code to 102.
func WithStatusProxyAuthRequired ¶
func WithStatusProxyAuthRequired() Option
WithStatusProxyAuthRequired sets the status code to 407.
func WithStatusRequestEntityTooLarge ¶
func WithStatusRequestEntityTooLarge() Option
WithStatusRequestEntityTooLarge sets the status code to 413.
func WithStatusRequestHeaderFieldsTooLarge ¶
func WithStatusRequestHeaderFieldsTooLarge() Option
WithStatusRequestHeaderFieldsTooLarge sets the status code to 431.
func WithStatusRequestTimeout ¶
func WithStatusRequestTimeout() Option
WithStatusRequestTimeout sets the status code to 408.
func WithStatusRequestURITooLong ¶
func WithStatusRequestURITooLong() Option
WithStatusRequestURITooLong sets the status code to 414.
func WithStatusRequestedRangeNotSatisfiable ¶
func WithStatusRequestedRangeNotSatisfiable() Option
WithStatusRequestedRangeNotSatisfiable sets the status code to 416.
func WithStatusResetContent ¶
func WithStatusResetContent() Option
WithStatusResetContent sets the status code to 205.
func WithStatusSeeOther ¶
func WithStatusSeeOther() Option
WithStatusSeeOther sets the status code to 303.
func WithStatusServiceUnavailable ¶
func WithStatusServiceUnavailable() Option
WithStatusServiceUnavailable sets the status code to 503.
func WithStatusSwitchingProtocols ¶
func WithStatusSwitchingProtocols() Option
WithStatusSwitchingProtocols sets the status code to 101.
func WithStatusTeapot ¶
func WithStatusTeapot() Option
WithStatusTeapot sets the status code to 418.
func WithStatusTemporaryRedirect ¶
func WithStatusTemporaryRedirect() Option
WithStatusTemporaryRedirect sets the status code to 307.
func WithStatusTooEarly ¶
func WithStatusTooEarly() Option
WithStatusTooEarly sets the status code to 425.
func WithStatusTooManyRequests ¶
func WithStatusTooManyRequests() Option
WithStatusTooManyRequests sets the status code to 429.
func WithStatusUnauthorized ¶
func WithStatusUnauthorized() Option
WithStatusUnauthorized sets the status code to 401.
func WithStatusUnavailableForLegalReasons ¶
func WithStatusUnavailableForLegalReasons() Option
WithStatusUnavailableForLegalReasons sets the status code to 451.
func WithStatusUnprocessableEntity ¶
func WithStatusUnprocessableEntity() Option
WithStatusUnprocessableEntity sets the status code to 422.
func WithStatusUnsupportedMediaType ¶
func WithStatusUnsupportedMediaType() Option
WithStatusUnsupportedMediaType sets the status code to 415.
func WithStatusUpgradeRequired ¶
func WithStatusUpgradeRequired() Option
WithStatusUpgradeRequired sets the status code to 426.
func WithStatusUseProxy ¶
func WithStatusUseProxy() Option
WithStatusUseProxy sets the status code to 305.
func WithStatusVariantAlsoNegotiates ¶
func WithStatusVariantAlsoNegotiates() Option
WithStatusVariantAlsoNegotiates sets the status code to 506.
func WithStreamJSON ¶
func WithStreamJSON() Option
WithStreamJSON switches JSON into streaming mode: the payload is encoded directly into the http.ResponseWriter instead of an intermediate buffer. This lowers memory use for very large responses, but trades away the buffered-mode guarantee - an encoding error may surface only after the status line and part of the body have already been written. Use it when you knowingly accept that trade-off. JSONP is always buffered (its body is trimmed and wrapped in the callback), so this option does not affect it.
type R ¶
R is a type alias for a map[string]any. It is designed to simplify the creation and manipulation of JSON objects in Go, making it easier to work with dynamic data structures commonly used in web applications and APIs. The use of `any` as the map value allows storing any Go value, offering the flexibility needed for JSON serialization.
The alias `R` stands for "Response", emphasizing its utility in preparing data for HTTP responses. It streamlines the generation of JSON-encoded responses by providing a concise and readable way to construct JSON objects without the need for struct definitions or type assertions.
Example Usage: The following example demonstrates how to use `R` to send a JSON response in an HTTP handler. The `resp.JSON` function leverages the `R` type to encode the map into a JSON object and write it to the HTTP response. This approach is particularly useful for endpoints that return JSON data, as it reduces boilerplate and improves code readability.
import (
"net/http"
"time"
"github.com/goloop/resp/v2"
)
func Handler(w http.ResponseWriter, r *http.Request) {
data := resp.R{
"Name": "Go Loop",
"Created": time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
}
if err := resp.JSON(w, data); err != nil {
// handle error
}
}
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response represents an HTTP response. It provides methods for setting headers, cookies, and writing data to the response body. It can be customized using various options.
Example Usage:
func Handler(w http.ResponseWriter, r *http.Request) {
response := resp.NewResponse(w, resp.WithStatus(http.StatusOK))
response.SetHeader("X-Custom-Header", "value")
response.JSON(resp.R{"message": "Hello, World!"})
}
func NewResponse ¶
func NewResponse(w http.ResponseWriter, opts ...Option) *Response
NewResponse creates a new instance of Response with the provided http.ResponseWriter and options. It applies the provided options to the response and returns the pointer to the created response.
Example Usage:
response := resp.NewResponse(w, resp.WithStatus(http.StatusOK),
resp.AsApplicationJSON(),
resp.ApplyJSONEncoder(customEncoder))
func (*Response) Accepted ¶
Accepted sends a 202 Accepted response with an optional JSON body. If data is nil, only the status is sent; otherwise data is encoded as JSON. An explicitly configured status code is respected, otherwise 202 is used.
func (*Response) AddHeader ¶
AddHeader adds into header with the provided key and value(s) and returns the modified response.
func (*Response) BindCookie ¶
BindCookie binds a cookie to the response. If a cookie with the same name already exists, it replaces the existing cookie with the new one.
If a cookie already exists, it will be deleted and a new one will be re-set. If there are multiple cookies with the same name, they will all be deleted.
func (*Response) Blob ¶
Blob sends raw bytes with an explicit content type. If contentType is empty, MIMEOctetStream is used. Content-Length is set automatically. This is the building block behind in-memory file/binary responses (PDF, images, pre-rendered documents) without a Content-Disposition.
func (*Response) ClearCookies ¶
ClearCookies deletes all cookies from the response and returns the modified response.
func (*Response) ClearHeaders ¶
ClearHeaders deletes all headers from the response and returns the modified response.
func (*Response) Created ¶
Created sends a 201 Created response with an optional Location header and an optional JSON body. If location is non-empty it is written to the Location header. If data is nil, only the status (and headers) are sent; otherwise data is encoded as JSON. An explicitly configured status code (via WithStatus/SetStatus) is respected, otherwise 201 is used.
func (*Response) DelCookie ¶
DelCookie deletes a cookie with the specified name from the response. It removes the cookie from the response's header and returns the modified response.
Pay attention. All cookies with this name will be deleted.
func (*Response) DelHeader ¶
DelHeader deletes the header with the provided key from the response and returns the modified response.
func (*Response) Error ¶
Error sends an error response as JSON.
The status argument is always the HTTP status code: it is written to the response status line AND, by default, mirrored into the JSON body's "code" field. Use WithErrorCode to override only the body code with a distinct application/business code while keeping the HTTP status intact.
The status argument takes precedence over any WithStatus option. If it is outside the valid HTTP range (100-599) it falls back to StatusInternalServerError. When message is empty, the canonical text for the status code is used.
func (*Response) ExpiredCookie ¶
ExpiredCookie expires a cookie with the specified name from the response.
func (*Response) GetJSONEncoder ¶
func (r *Response) GetJSONEncoder() JSONEncodeFunc
GetJSONEncoder returns the JSON encoder function of the response. If the JSON encoder function is not set, it returns nil.
func (*Response) HTML ¶
HTML sends an HTML response. If the status code is not set - StatusOK will be set. If ContentType isn't defined - MIMETextHTMLCharsetUTF8 is used.
func (*Response) Header ¶
Header returns the underlying response header map, allowing callers to read or modify headers directly. It is the same map returned by the wrapped http.ResponseWriter.Header.
func (*Response) JSON ¶
JSON sends a JSON response. If the status code is not set - StatusOK will be set. If ContentType isn't defined - MIMEApplicationJSON will be used by default.
By default the payload is encoded into an in-memory buffer first, so that a serialization failure is reported BEFORE the status line is written and the calling handler can still respond with a proper error. Opt into zero-copy streaming with WithStreamJSON when memory matters more than this guarantee (see WithStreamJSON for the trade-offs).
func (*Response) JSONIndent ¶
JSONIndent sends an indented (pretty-printed) JSON response — handy for human-facing or debug endpoints. Unlike JSON it always uses the standard library encoder with the given prefix and indent, ignoring any custom encoder set via ApplyJSONEncoder (indentation is the whole point). Encoding is buffered, so an error is reported before the status line is committed.
func (*Response) JSONP ¶
JSONP sends a JSONP response. If the status code is not set - StatusOK will be set. If ContentType isn't defined - MIMEApplicationJavaScript will be used by default.
The callback name is validated against a strict JavaScript-identifier whitelist before anything is written. An unsafe name (containing quotes, brackets, markup, etc.) yields ErrInvalidJSONPCallback and no output, which prevents the callback padding from becoming a reflected-XSS vector.
func (*Response) Redirect ¶
Redirect sends an HTTP redirect to the specified URL.
Only genuine redirect status codes are honoured: 300, 301, 302, 303, 307 and 308. Any other configured status (including the non-redirect 304, 305 and 306) falls back to StatusFound (302). This method always returns nil.
Security: the url is written verbatim into the Location header. If it originates from user input, validate it (e.g. allow only relative paths or an allow-listed host) before calling Redirect to avoid an open-redirect.
func (*Response) ServeFile ¶
ServeFile sends a file response.
It delegates to http.ServeFile, which writes the status code, headers and body itself (including 404 handling, range requests and content sniffing). Because http.ServeFile manages the whole exchange, this method always returns nil; inspect the written response (e.g. via a recorder) rather than the return value to detect failures.
func (*Response) ServeFileAsDownload ¶
ServeFileAsDownload sends in-memory data as a downloadable file.
It sets Content-Disposition (with an RFC 5987 UTF-8 form so non-ASCII file names survive), Content-Length from len(data), and X-Content-Type-Options: nosniff to stop browsers from re-sniffing the type. The content type defaults to MIMEOctetStream but is preserved if a caller set one explicitly via options.
func (*Response) SetCookie ¶
SetCookie sets a cookie in the response and returns the modified response.
func (*Response) SetHeader ¶
SetHeader sets the header with the provided key and value(s) and returns the modified response.
func (*Response) SetJSONEncoder ¶
func (r *Response) SetJSONEncoder(f JSONEncodeFunc) *Response
SetJSONEncoder sets the custom JSON encoder function for the response and returns pointer to the modified response object.
func (*Response) SetStatus ¶
SetStatus sets the status code of the response and returns the modified response.
func (*Response) Status ¶
Status returns the status code currently configured for the response. Before any status is set (via SetStatus, WithStatus or a terminal write method) it returns StatusUndefined (0). This is primarily useful for middleware and tests that need to inspect the intended status.
func (*Response) String ¶
String sends a string response. If the status code is not set - StatusOK will be set. If ContentType isn't defined - MIMETextPlain will be used by default.