Movatterモバイル変換


[0]ホーム

URL:


httpapi

package
v2.23.0Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License:AGPL-3.0Imports:24Imported by:0

Details

Repository

github.com/coder/coder

Links

Documentation

Index

Constants

View Source
const HeartbeatIntervaltime.Duration = 15 *time.Second
View Source
const (// XForwardedHostHeader is a header used by proxies to indicate the// original host of the request.XForwardedHostHeader = "X-Forwarded-Host")

Variables

View Source
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.",}
View Source
var ResourceNotFoundResponse =codersdk.Response{Message: "Resource not found or you do not have access to this resource"}
View Source
var Validate *validator.Validate

Functions

funcForbidden

func Forbidden(rwhttp.ResponseWriter)

funcHeartbeat

func Heartbeat(ctxcontext.Context, conn *websocket.Conn)

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

funcHeartbeatClose

func HeartbeatClose(ctxcontext.Context, loggerslog.Logger, exit func(), conn *websocket.Conn)

Heartbeat loops to ping a WebSocket to keep it alive. It calls `exit` on pingfailure.

funcInternalServerError

func InternalServerError(rwhttp.ResponseWriter, errerror)

funcIs404Error

func Is404Error(errerror)bool

Is404Error returns true if the given error should return a 404 status code.Both actual 404s and unauthorized errors should return 404s to not leakinformation about the existence of resources.

funcIsUnauthorizedErroradded inv2.15.0

func IsUnauthorizedError(errerror)bool

funcIsWebsocketUpgrade

func IsWebsocketUpgrade(r *http.Request)bool

funcOneWayWebSocketEventSenderadded inv2.22.0

func OneWayWebSocketEventSender(rwhttp.ResponseWriter, r *http.Request) (func(eventcodersdk.ServerSentEvent)error,<-chan struct{},error,)

OneWayWebSocketEventSender establishes a new WebSocket connection thatenforces one-way communication from the server to the client.

The function returned allows you to send a single message to the client,while the channel lets you listen for when the connection closes.

We must use an approach like this instead of Server-Sent Events for thebrowser, because on HTTP/1.1 connections, browsers are locked to no more thansix HTTP connections for a domain total, across all tabs. If a user were toopen a workspace in multiple tabs, the entire UI can start to lock up.WebSockets have no such limitation, no matter what HTTP protocol was used toestablish the connection.

funcParseCustom

func ParseCustom[Tany](parser *QueryParamParser, valsurl.Values, def T, queryParamstring, parseFunc func(vstring) (T,error)) T

ParseCustom has to be a function, not a method on QueryParamParser because genericscannot be used on struct methods.

funcParseCustomList

func ParseCustomList[Tany](parser *QueryParamParser, valsurl.Values, def []T, queryParamstring, parseFunc func(vstring) (T,error)) []T

ParseCustomList is a function that handles csv query params or multiple valuesfor 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.

funcParseEnum

func ParseEnum[TValidEnum](termstring) (T,error)

ParseEnum is a function that can be passed into ParseCustom that handles enumvalidation.

funcRead

func Read(ctxcontext.Context, rwhttp.ResponseWriter, r *http.Request, value interface{})bool

Read decodes JSON from the HTTP request into the value provided. It usesgo-validator to validate the incoming request body. ctx is used for tracingand can be nil. Although tracing this function isn't likely too helpful, itwas done to be consistent with Write.

funcRequestHost

func RequestHost(r *http.Request)string

RequestHost returns the name of the host from the request. It prioritizes'X-Forwarded-Host' over r.Host since most requests are being proxied.

funcResourceNotFound

func ResourceNotFound(rwhttp.ResponseWriter)

ResourceNotFound is intentionally vague. All 404 responses should be identicalto prevent leaking existence of resources.

funcRouteNotFound

func RouteNotFound(rwhttp.ResponseWriter)

funcServerSentEventSender

func ServerSentEventSender(rwhttp.ResponseWriter, r *http.Request) (func(ssecodersdk.ServerSentEvent)error,<-chan struct{},error,)

ServerSentEventSender establishes a Server-Sent Event connection and allowsthe consumer to send messages to the client.

The function returned allows you to send a single message to the client,while the channel lets you listen for when the connection closes.

As much as possible, this function should be avoided in favor of using theOneWayWebSocket function. See OneWayWebSocket for more context.

funcSetAuthzCheckRecorderHeaderadded inv2.23.0

func SetAuthzCheckRecorderHeader(ctxcontext.Context, rwhttp.ResponseWriter)

This is defined separately in slim builds to avoid importing the rbacpackage, which is a large dependency.

funcStripCoderCookies

func StripCoderCookies(headerstring)string

StripCoderCookies removes the session token from the cookie header provided.

funcWebsocketCloseSprintf

func WebsocketCloseSprintf(formatstring, vars ...any)string

WebsocketCloseSprintf formats a websocket close message and ensures it istruncated to the maximum allowed length.

funcWrite

func Write(ctxcontext.Context, rwhttp.ResponseWriter, statusint, response interface{})

Write outputs a standardized format to an HTTP response body. ctx is used fortracing and can be nil for tracing to be disabled. Tracing this function ishelpful because JSON marshaling can sometimes take a non-insignificant amountof time, and could help us catch outliers. Additionally, we can enrich spandata a bit more since we have access to the actual interface{} we'remarshaling, such as the number of elements in an array, which could help usspot routes that need to be paginated.

funcWriteIndent

func WriteIndent(ctxcontext.Context, rwhttp.ResponseWriter, statusint, response interface{})

Types

typeDuration

type Durationtime.Duration

Duration wraps time.Duration and provides better JSON marshaling andunmarshalling. The default time.Duration marshals as an integer and onlyaccepts integers when unmarshalling, which is not very user friendly as userscannot write durations like "1h30m".

This type marshals as a string like "1h30m", and unmarshals from either astring or an integer.

func (Duration)MarshalJSON

func (dDuration) MarshalJSON() ([]byte,error)

MarshalJSON implements json.Marshaler.

func (*Duration)UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte)error

UnmarshalJSON implements json.Unmarshaler.

typeEventSenderadded inv2.22.0

type EventSender func(rwhttp.ResponseWriter, r *http.Request) (sendEvent func(ssecodersdk.ServerSentEvent)error,done <-chan struct{},errerror,)

typeNoopResponseWriteradded inv2.21.1

type NoopResponseWriter struct{}

NoopResponseWriter is a response writer that does nothing.

func (NoopResponseWriter)Headeradded inv2.21.1

func (NoopResponseWriter)Writeadded inv2.21.1

func (NoopResponseWriter) Write(p []byte) (int,error)

func (NoopResponseWriter)WriteHeaderadded inv2.21.1

func (NoopResponseWriter) WriteHeader(int)

typeQueryParamParser

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 allerrors in 1 sweep. This means all invalid fields are returned at once,rather than only returning the first error

funcNewQueryParamParser

func NewQueryParamParser() *QueryParamParser

func (*QueryParamParser)Booleanadded inv2.3.0

func (p *QueryParamParser) Boolean(valsurl.Values, defbool, queryParamstring)bool

func (*QueryParamParser)ErrorExcessParams

func (p *QueryParamParser) ErrorExcessParams(valuesurl.Values)

ErrorExcessParams checks if any query params were passed in that were notparsed. If so, it adds an error to the parser as these values are not validquery parameters.

func (*QueryParamParser)Int

func (p *QueryParamParser) Int(valsurl.Values, defint, queryParamstring)int

func (*QueryParamParser)Int64added inv2.21.0

func (p *QueryParamParser) Int64(valsurl.Values, defint64, queryParamstring)int64

func (*QueryParamParser)JSONStringMapadded inv2.20.0

func (p *QueryParamParser) JSONStringMap(valsurl.Values, def map[string]string, queryParamstring) map[string]string

func (*QueryParamParser)NullableBooleanadded inv2.14.0

func (p *QueryParamParser) NullableBoolean(valsurl.Values, defsql.NullBool, queryParamstring)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 fromthe generic type is required.

func (*QueryParamParser)PositiveInt32added inv2.9.0

func (p *QueryParamParser) PositiveInt32(valsurl.Values, defint32, queryParamstring)int32

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)RedirectURLadded inv2.9.0

func (p *QueryParamParser) RedirectURL(valsurl.Values, base *url.URL, queryParamstring) *url.URL

func (*QueryParamParser)RequiredNotEmptyadded inv2.9.0

func (p *QueryParamParser) RequiredNotEmpty(queryParam ...string) *QueryParamParser

func (*QueryParamParser)String

func (p *QueryParamParser) String(valsurl.Values, defstring, queryParamstring)string

func (*QueryParamParser)Strings

func (p *QueryParamParser) Strings(valsurl.Values, def []string, queryParamstring) []string

func (*QueryParamParser)Time

func (p *QueryParamParser) Time(valsurl.Values, deftime.Time, queryParam, layoutstring)time.Time

func (*QueryParamParser)Time3339Nano

func (p *QueryParamParser) Time3339Nano(valsurl.Values, deftime.Time, queryParamstring)time.Time

Time uses the default time format of RFC3339Nano and always returns a UTC time.

func (*QueryParamParser)UInt

func (p *QueryParamParser) UInt(valsurl.Values, defuint64, queryParamstring)uint64

func (*QueryParamParser)UUID

func (p *QueryParamParser) UUID(valsurl.Values, defuuid.UUID, queryParamstring)uuid.UUID

func (*QueryParamParser)UUIDorMe

func (p *QueryParamParser) UUIDorMe(valsurl.Values, defuuid.UUID, meuuid.UUID, queryParamstring)uuid.UUID

func (*QueryParamParser)UUIDorNameadded inv2.15.0

func (p *QueryParamParser) UUIDorName(valsurl.Values, defuuid.UUID, queryParamstring, fetchByName func(namestring) (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.

func (*QueryParamParser)UUIDs

func (p *QueryParamParser) UUIDs(valsurl.Values, def []uuid.UUID, queryParamstring) []uuid.UUID

typeValidEnum

type ValidEnum interface {~string// Valid is required on the enum type to be used with ParseEnum.Valid()bool}

ValidEnum represents an enum that can be parsed and validated.

Source Files

View all Source files

Directories

PathSynopsis
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp