Documentation
¶
Index ¶
- Constants
- Variables
- func Forbidden(rw http.ResponseWriter)
- func Heartbeat(ctx context.Context, conn *websocket.Conn)
- func HeartbeatClose(ctx context.Context, logger slog.Logger, exit func(), conn *websocket.Conn)
- func InternalServerError(rw http.ResponseWriter, err error)
- func Is404Error(err error) bool
- func IsUnauthorizedError(err error) bool
- func IsWebsocketUpgrade(r *http.Request) bool
- func ParseCustom[T any](parser *QueryParamParser, vals url.Values, def T, queryParam string, ...) T
- func ParseCustomList[T any](parser *QueryParamParser, vals url.Values, def []T, queryParam string, ...) []T
- func ParseEnum[T ValidEnum](term string) (T, error)
- func Read(ctx context.Context, rw http.ResponseWriter, r *http.Request, ...) bool
- func RequestHost(r *http.Request) string
- func ResourceNotFound(rw http.ResponseWriter)
- func RouteNotFound(rw http.ResponseWriter)
- func ServerSentEventSender(rw http.ResponseWriter, r *http.Request) (sendEvent func(ctx context.Context, sse codersdk.ServerSentEvent) error, ...)
- func StripCoderCookies(header string) string
- func WebsocketCloseSprintf(format string, vars ...any) string
- func Write(ctx context.Context, rw http.ResponseWriter, status int, response interface{})
- func WriteIndent(ctx context.Context, rw http.ResponseWriter, status int, response interface{})
- type Duration
- type NoopResponseWriter
- type QueryParamParser
- func (p *QueryParamParser) Boolean(vals url.Values, def bool, queryParam string) bool
- func (p *QueryParamParser) ErrorExcessParams(values url.Values)
- func (p *QueryParamParser) Int(vals url.Values, def int, queryParam string) int
- func (p *QueryParamParser) Int64(vals url.Values, def int64, queryParam string) int64
- func (p *QueryParamParser) JSONStringMap(vals url.Values, def map[string]string, queryParam string) map[string]string
- func (p *QueryParamParser) NullableBoolean(vals url.Values, def sql.NullBool, queryParam string) sql.NullBool
- func (p *QueryParamParser) PositiveInt32(vals url.Values, def int32, queryParam string) int32
- func (p *QueryParamParser) RedirectURL(vals url.Values, base *url.URL, queryParam string) *url.URL
- func (p *QueryParamParser) RequiredNotEmpty(queryParam ...string) *QueryParamParser
- func (p *QueryParamParser) String(vals url.Values, def string, queryParam string) string
- func (p *QueryParamParser) Strings(vals url.Values, def []string, queryParam string) []string
- func (p *QueryParamParser) Time(vals url.Values, def time.Time, queryParam, layout string) time.Time
- func (p *QueryParamParser) Time3339Nano(vals url.Values, def time.Time, queryParam string) time.Time
- func (p *QueryParamParser) UInt(vals url.Values, def uint64, queryParam string) uint64
- func (p *QueryParamParser) UUID(vals url.Values, def uuid.UUID, queryParam string) uuid.UUID
- func (p *QueryParamParser) UUIDorMe(vals url.Values, def uuid.UUID, me uuid.UUID, queryParam string) uuid.UUID
- func (p *QueryParamParser) UUIDorName(vals url.Values, def uuid.UUID, queryParam string, ...) uuid.UUID
- func (p *QueryParamParser) UUIDs(vals url.Values, def []uuid.UUID, queryParam string) []uuid.UUID
- type ValidEnum
Constants ¶
const ( // XForwardedHostHeader is a header used by proxies to indicate the // original host of the request. XForwardedHostHeader = "X-Forwarded-Host" )
Variables ¶
var ResourceForbiddenResponse = codersdk.Response{
Message: "Forbidden.",
Detail: "You don't have permission to view this content. If you believe this is a mistake, please contact your administrator or try signing in with different credentials.",
}
var ResourceNotFoundResponse = codersdk.Response{Message: "Resource not found or you do not have access to this resource"}
var Validate *validator.Validate
Functions ¶
func Forbidden ¶
func Forbidden(rw http.ResponseWriter)
func Heartbeat ¶
Heartbeat loops to ping a WebSocket to keep it alive. Default idle connection timeouts are typically 60 seconds. See: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html#connection-idle-timeout
func HeartbeatClose ¶
Heartbeat loops to ping a WebSocket to keep it alive. It calls `exit` on ping failure.
func InternalServerError ¶
func InternalServerError(rw http.ResponseWriter, err error)
func Is404Error ¶
Is404Error returns true if the given error should return a 404 status code. Both actual 404s and unauthorized errors should return 404s to not leak information about the existence of resources.
func IsUnauthorizedError ¶ added in v2.15.0
func IsWebsocketUpgrade ¶
func ParseCustom ¶
func ParseCustom[T any](parser *QueryParamParser, vals url.Values, def T, queryParam string, parseFunc func(v string) (T, error)) T
ParseCustom has to be a function, not a method on QueryParamParser because generics cannot be used on struct methods.
func ParseCustomList ¶
func ParseCustomList[T any](parser *QueryParamParser, vals url.Values, def []T, queryParam string, parseFunc func(v string) (T, error)) []T
ParseCustomList is a function that handles csv query params or multiple values for a query param. Csv is supported as it is a common way to pass multiple values in a query param. Multiple values is supported (key=value&key=value2) for feature parity with GitHub issue search.
func ParseEnum ¶
ParseEnum is a function that can be passed into ParseCustom that handles enum validation.
func Read ¶
Read decodes JSON from the HTTP request into the value provided. It uses go-validator to validate the incoming request body. ctx is used for tracing and can be nil. Although tracing this function isn't likely too helpful, it was done to be consistent with Write.
func RequestHost ¶
RequestHost returns the name of the host from the request. It prioritizes 'X-Forwarded-Host' over r.Host since most requests are being proxied.
func ResourceNotFound ¶
func ResourceNotFound(rw http.ResponseWriter)
ResourceNotFound is intentionally vague. All 404 responses should be identical to prevent leaking existence of resources.
func RouteNotFound ¶
func RouteNotFound(rw http.ResponseWriter)
func ServerSentEventSender ¶
func ServerSentEventSender(rw http.ResponseWriter, r *http.Request) (sendEvent func(ctx context.Context, sse codersdk.ServerSentEvent) error, closed chan struct{}, err error)
func StripCoderCookies ¶
StripCoderCookies removes the session token from the cookie header provided.
func WebsocketCloseSprintf ¶
WebsocketCloseSprintf formats a websocket close message and ensures it is truncated to the maximum allowed length.
func Write ¶
func Write(ctx context.Context, rw http.ResponseWriter, status int, response interface{})
Write outputs a standardized format to an HTTP response body. ctx is used for tracing and can be nil for tracing to be disabled. Tracing this function is helpful because JSON marshaling can sometimes take a non-insignificant amount of time, and could help us catch outliers. Additionally, we can enrich span data a bit more since we have access to the actual interface{} we're marshaling, such as the number of elements in an array, which could help us spot routes that need to be paginated.
func WriteIndent ¶
func WriteIndent(ctx context.Context, rw http.ResponseWriter, status int, response interface{})
Types ¶
type Duration ¶
Duration wraps time.Duration and provides better JSON marshaling and unmarshalling. The default time.Duration marshals as an integer and only accepts integers when unmarshalling, which is not very user friendly as users cannot write durations like "1h30m".
This type marshals as a string like "1h30m", and unmarshals from either a string or an integer.
func (Duration) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type NoopResponseWriter ¶ added in v2.21.1
type NoopResponseWriter struct{}
NoopResponseWriter is a response writer that does nothing.
func (NoopResponseWriter) Header ¶ added in v2.21.1
func (NoopResponseWriter) Header() http.Header
func (NoopResponseWriter) Write ¶ added in v2.21.1
func (NoopResponseWriter) Write(p []byte) (int, error)
func (NoopResponseWriter) WriteHeader ¶ added in v2.21.1
func (NoopResponseWriter) WriteHeader(int)
type QueryParamParser ¶
type QueryParamParser struct { // Errors is the set of errors to return via the API. If the length // of this set is 0, there are no errors!. Errors []codersdk.ValidationError // Parsed is a map of all query params that were parsed. This is useful // for checking if extra query params were passed in. Parsed map[string]bool // RequiredNotEmptyParams is a map of all query params that are required. This is useful // for forcing a value to be provided. RequiredNotEmptyParams map[string]bool }
QueryParamParser is a helper for parsing all query params and gathering all errors in 1 sweep. This means all invalid fields are returned at once, rather than only returning the first error
func NewQueryParamParser ¶
func NewQueryParamParser() *QueryParamParser
func (*QueryParamParser) ErrorExcessParams ¶
func (p *QueryParamParser) ErrorExcessParams(values url.Values)
ErrorExcessParams checks if any query params were passed in that were not parsed. If so, it adds an error to the parser as these values are not valid query parameters.
func (*QueryParamParser) JSONStringMap ¶ added in v2.20.0
func (*QueryParamParser) NullableBoolean ¶ added in v2.14.0
func (p *QueryParamParser) NullableBoolean(vals url.Values, def sql.NullBool, queryParam string) sql.NullBool
NullableBoolean will return a null sql value if no input is provided. SQLc still uses sql.NullBool rather than the generic type. So converting from the generic type is required.
func (*QueryParamParser) PositiveInt32 ¶ added in v2.9.0
PositiveInt32 function checks if the given value is 32-bit and positive.
We can't use `uint32` as the value must be within the range <0,2147483647> as database expects it. Otherwise, the database query fails with `pq: OFFSET must not be negative`.
func (*QueryParamParser) RedirectURL ¶ added in v2.9.0
func (*QueryParamParser) RequiredNotEmpty ¶ added in v2.9.0
func (p *QueryParamParser) RequiredNotEmpty(queryParam ...string) *QueryParamParser
func (*QueryParamParser) Time3339Nano ¶
func (p *QueryParamParser) Time3339Nano(vals url.Values, def time.Time, queryParam string) time.Time
Time uses the default time format of RFC3339Nano and always returns a UTC time.
func (*QueryParamParser) UUIDorName ¶ added in v2.15.0
func (p *QueryParamParser) UUIDorName(vals url.Values, def uuid.UUID, queryParam string, fetchByName func(name string) (uuid.UUID, error)) uuid.UUID
UUIDorName will parse a string as a UUID, if it fails, it uses the "fetchByName" function to return a UUID based on the value as a string. This is useful when fetching something like an organization by ID or by name.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package httpapiconstraints contain types that can be used and implemented across the application to return specific HTTP status codes without pulling in large dependency trees.
|
Package httpapiconstraints contain types that can be used and implemented across the application to return specific HTTP status codes without pulling in large dependency trees. |