rest

package
v0.42.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContentTypeJSON    = "application/json"
	ContentTypeMsgPack = "application/msgpack"
)

Variables

This section is empty.

Functions

func AcceptsGzip added in v0.37.0

func AcceptsGzip(r *http.Request) bool

AcceptsGzip reports whether the request accepts a gzip-encoded response.

func DecodeMsgPack added in v0.32.0

func DecodeMsgPack(r io.Reader, v any) error

DecodeMsgPack fully drains r and decodes the MessagePack payload into v.

Do not call msgpack.UnmarshalRead on a real io.Reader: shamaton's stream decoder issues one Read per field and discards the byte count, so any short read (routine over HTTP/2 / chunked bodies) silently corrupts the decode.

func DecodeRequestBody

func DecodeRequestBody(w http.ResponseWriter, r *http.Request, v interface{}) error

DecodeRequestBody decodes JSON or Msgpack data from the request body into a struct

func DecodeResponse added in v0.37.0

func DecodeResponse(resp *http.Response, response interface{}) error

DecodeResponse turns a non-2xx response into an error carrying the server's message, otherwise decodes the body into response when it is not nil.

func EncodeMsgPack added in v0.32.0

func EncodeMsgPack(w io.Writer, v any) error

EncodeMsgPack marshals v and writes the full MessagePack payload to w, looping the write to honour the io.Writer contract (MarshalWrite can short-write and truncate).

func GunzipRequest added in v0.37.0

func GunzipRequest(r *http.Request) error

GunzipRequest decodes a request body sent with Content-Encoding: gzip.

func Gzip added in v0.37.0

func Gzip(next http.HandlerFunc) http.HandlerFunc

Gzip compresses the response of next for clients that accept it. It is for responses of records (listings, change feeds, backups) that are large and compress well; file content is sent as stored, so its checksums, ranges and ETags hold. A handler that flushes still streams.

func IsStatus added in v0.37.0

func IsStatus(err error, codes ...int) bool

IsStatus reports whether err carries any of the given HTTP status codes.

func NewMuxHTTPClient added in v0.23.0

func NewMuxHTTPClient(user *model.User) *http.Client

NewMuxHTTPClient creates an *http.Client that routes requests through the API mux with the given user injected into context for authentication. This allows standard HTTP clients (like mcpopenai.Client) to make in-process API calls without needing a valid auth token.

func NoDeadlines added in v0.37.0

func NoDeadlines(w http.ResponseWriter)

NoDeadlines lifts the server's read and write timeouts on a request, for transfers of unbounded size.

func SetAPIMux added in v0.23.0

func SetAPIMux(mux *http.ServeMux)

SetAPIMux stores the API mux for direct calls

func StatusOf added in v0.37.0

func StatusOf(err error) int

StatusOf returns the HTTP status code carried by err, or 0 when err is not (or does not wrap) an HTTPError.

func StreamData

func StreamData[P Pointer[T], T any](
	c *HTTPClient,
	ctx context.Context,
	method string,
	path string,
	request interface{},
	fn func(P) (bool, error),
) error

Thin generic wrapper - only this small function is duplicated per type

func WithoutTimeout added in v0.42.0

func WithoutTimeout(ctx context.Context) context.Context

WithoutTimeout marks a request's context so the client's timeout does not apply to it, for a call that may rightly take longer, such as a command run with a timeout of its own: only ctx bounds it.

func WriteResponse

func WriteResponse(status int, w http.ResponseWriter, r *http.Request, v interface{}) error

WriteResponse encodes and writes a JSON or Msgpack response

Types

type HTTPClient added in v0.23.0

type HTTPClient struct {
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

func NewClient

func NewClient(baseURL string, token string, insecureSkipVerify bool) (*HTTPClient, error)

func NewUnixSocketClient added in v0.23.7

func NewUnixSocketClient(host string) (*HTTPClient, error)

NewUnixSocketClient creates an HTTPClient that communicates over a Unix socket or plain TCP, depending on the host string format (same formats Docker accepts). No TLS, no HTTP/2 — Docker/Podman sockets don't use them.

func (*HTTPClient) AppendUserAgent added in v0.23.0

func (c *HTTPClient) AppendUserAgent(userAgent string) RESTClient

func (*HTTPClient) ClearHeaders added in v0.23.0

func (c *HTTPClient) ClearHeaders() RESTClient

func (*HTTPClient) Close added in v0.23.0

func (c *HTTPClient) Close()

func (*HTTPClient) Delete added in v0.23.0

func (c *HTTPClient) Delete(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*HTTPClient) DeleteHeader added in v0.23.0

func (c *HTTPClient) DeleteHeader(key string) RESTClient

func (*HTTPClient) DoRaw added in v0.37.0

func (c *HTTPClient) DoRaw(ctx context.Context, method string, path string, body io.Reader, size int64, headers map[string]string) (*http.Response, error)

DoRaw sends a request with a streamed body and returns the raw response, leaving the body for the caller to read and close. size is the body length, -1 if unknown. Unlike the JSON helpers it applies no overall timeout, so large transfers are bounded only by ctx.

func (*HTTPClient) Get added in v0.23.0

func (c *HTTPClient) Get(ctx context.Context, path string, response interface{}) (int, error)

func (*HTTPClient) GetAuthToken added in v0.23.0

func (c *HTTPClient) GetAuthToken() string

func (*HTTPClient) GetBaseURL added in v0.23.0

func (c *HTTPClient) GetBaseURL() string

func (*HTTPClient) GetJSON added in v0.23.0

func (c *HTTPClient) GetJSON(ctx context.Context, path string, response interface{}) (int, error)

GetJSON sends a GET request with JSON accept header (thread-safe)

func (*HTTPClient) Post added in v0.23.0

func (c *HTTPClient) Post(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*HTTPClient) PostJSON added in v0.23.0

func (c *HTTPClient) PostJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

PostJSON sends a POST request with JSON content type and JSON accept header (thread-safe)

func (*HTTPClient) PostWithContentType added in v0.23.0

func (c *HTTPClient) PostWithContentType(ctx context.Context, path string, request interface{}, response interface{}, successCode int, contentType string) (int, error)

func (*HTTPClient) Put added in v0.23.0

func (c *HTTPClient) Put(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*HTTPClient) PutJSON added in v0.23.0

func (c *HTTPClient) PutJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

PutJSON sends a PUT request with JSON content type and JSON accept header (thread-safe)

func (*HTTPClient) PutWithContentType added in v0.23.0

func (c *HTTPClient) PutWithContentType(ctx context.Context, path string, request interface{}, response interface{}, successCode int, contentType string) (int, error)

func (*HTTPClient) SendData added in v0.23.0

func (c *HTTPClient) SendData(ctx context.Context, method string, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*HTTPClient) SendDataWithContentType added in v0.23.0

func (c *HTTPClient) SendDataWithContentType(ctx context.Context, method string, path string, request interface{}, response interface{}, successCode int, contentType string) (int, error)

SendDataWithContentType sends a request with a specific content type (thread-safe)

func (*HTTPClient) SendDataWithContentTypeAndAccept added in v0.23.0

func (c *HTTPClient) SendDataWithContentTypeAndAccept(ctx context.Context, method string, path string, request interface{}, response interface{}, successCode int, contentType string, accept string) (int, error)

SendDataWithContentTypeAndAccept sends a request with specific content type and accept header (thread-safe)

func (*HTTPClient) SetAccept added in v0.23.0

func (c *HTTPClient) SetAccept(accept ...string) RESTClient

func (*HTTPClient) SetAuthToken added in v0.23.0

func (c *HTTPClient) SetAuthToken(token string) RESTClient

func (*HTTPClient) SetBaseUrl added in v0.23.0

func (c *HTTPClient) SetBaseUrl(baseURL string) (RESTClient, error)

func (*HTTPClient) SetContentType added in v0.23.0

func (c *HTTPClient) SetContentType(contentType string) RESTClient

func (*HTTPClient) SetHeader added in v0.23.0

func (c *HTTPClient) SetHeader(key, value string) RESTClient

func (*HTTPClient) SetResponseCheck added in v0.41.0

func (c *HTTPClient) SetResponseCheck(check func(*http.Response) error) RESTClient

SetResponseCheck vets every reply with check before it's read.

func (*HTTPClient) SetTimeout added in v0.23.0

func (c *HTTPClient) SetTimeout(timeout time.Duration) RESTClient

func (*HTTPClient) SetTokenFormat added in v0.23.0

func (c *HTTPClient) SetTokenFormat(format string) RESTClient

func (*HTTPClient) SetTokenKey added in v0.23.0

func (c *HTTPClient) SetTokenKey(key string) RESTClient

func (*HTTPClient) SetUserAgent added in v0.23.0

func (c *HTTPClient) SetUserAgent(userAgent string) RESTClient

type HTTPError added in v0.37.0

type HTTPError struct {
	StatusCode int
	Method     string
	Path       string
	// Server is the scheme and host the request went to, when known
	// (empty for in-process mux calls).
	Server string
	// ServerMessage is the server's explanation, already unwrapped from the
	// JSON/msgpack error envelope. It may be empty.
	ServerMessage string
}

HTTPError is returned by the REST clients when the server answers with a status other than the one the caller expected. It carries the status code, the request that failed and the server's own message (the "error" field of knot's {"error": "..."} envelope, or the raw body when there is no envelope), so callers can branch on the status with errors.As or the StatusOf / IsStatus helpers instead of parsing strings.

Error() keeps the historical "unexpected status code: N: message" wording: scripts, the agent link and older callers match on that prefix. Use Message() for the server's text alone, or Summary() for a phrase fit to show a person.

func AsHTTPError added in v0.37.0

func AsHTTPError(err error) *HTTPError

AsHTTPError returns the HTTPError in err's chain, or nil.

func NewHTTPError added in v0.37.0

func NewHTTPError(statusCode int, method, path string, body []byte) *HTTPError

NewHTTPError builds an HTTPError from a response body, decoding knot's error envelope when present.

func (*HTTPError) Error added in v0.37.0

func (e *HTTPError) Error() string

func (*HTTPError) Message added in v0.37.0

func (e *HTTPError) Message() string

Message returns the server's explanation, or the standard status text when the server gave none.

func (*HTTPError) Summary added in v0.37.0

func (e *HTTPError) Summary() string

Summary returns a plain-language description of the failure followed by the status code, e.g. "no permission to manage users (403)". When the server gave no message a description of the status is used instead.

type MuxClient added in v0.23.0

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

MuxClient calls API handlers directly via mux without HTTP overhead

func (*MuxClient) AppendUserAgent added in v0.23.0

func (c *MuxClient) AppendUserAgent(userAgent string) RESTClient

func (*MuxClient) ClearHeaders added in v0.23.0

func (c *MuxClient) ClearHeaders() RESTClient

func (*MuxClient) Delete added in v0.23.0

func (c *MuxClient) Delete(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*MuxClient) DeleteHeader added in v0.23.0

func (c *MuxClient) DeleteHeader(key string) RESTClient

func (*MuxClient) DoRaw added in v0.37.0

func (c *MuxClient) DoRaw(ctx context.Context, method string, path string, body io.Reader, size int64, headers map[string]string) (*http.Response, error)

DoRaw sends a request with a raw body and extra headers through the mux and returns the response unread, so callers can move bytes rather than JSON. It matches HTTPClient.DoRaw, letting raw transfers work in either client.

func (*MuxClient) Get added in v0.23.0

func (c *MuxClient) Get(ctx context.Context, path string, response interface{}) (int, error)

func (*MuxClient) GetAuthToken added in v0.23.0

func (c *MuxClient) GetAuthToken() string

func (*MuxClient) GetBaseURL added in v0.23.0

func (c *MuxClient) GetBaseURL() string

func (*MuxClient) GetJSON added in v0.23.0

func (c *MuxClient) GetJSON(ctx context.Context, path string, response interface{}) (int, error)

func (*MuxClient) Post added in v0.23.0

func (c *MuxClient) Post(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*MuxClient) PostJSON added in v0.23.0

func (c *MuxClient) PostJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*MuxClient) Put added in v0.23.0

func (c *MuxClient) Put(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*MuxClient) PutJSON added in v0.23.0

func (c *MuxClient) PutJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)

func (*MuxClient) RoundTrip added in v0.23.0

func (c *MuxClient) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper by routing the request through the API mux with the user injected into context for authentication.

func (*MuxClient) SetAccept added in v0.23.0

func (c *MuxClient) SetAccept(accept ...string) RESTClient

func (*MuxClient) SetAuthToken added in v0.23.0

func (c *MuxClient) SetAuthToken(token string) RESTClient

func (*MuxClient) SetBaseUrl added in v0.23.0

func (c *MuxClient) SetBaseUrl(baseURL string) (RESTClient, error)

func (*MuxClient) SetContentType added in v0.23.0

func (c *MuxClient) SetContentType(contentType string) RESTClient

func (*MuxClient) SetHeader added in v0.23.0

func (c *MuxClient) SetHeader(key, value string) RESTClient

func (*MuxClient) SetResponseCheck added in v0.41.0

func (c *MuxClient) SetResponseCheck(check func(*http.Response) error) RESTClient

SetResponseCheck is a no-op: a MuxClient calls its own server.

func (*MuxClient) SetTimeout added in v0.23.0

func (c *MuxClient) SetTimeout(timeout time.Duration) RESTClient

func (*MuxClient) SetTokenFormat added in v0.23.0

func (c *MuxClient) SetTokenFormat(format string) RESTClient

func (*MuxClient) SetTokenKey added in v0.23.0

func (c *MuxClient) SetTokenKey(key string) RESTClient

func (*MuxClient) SetUserAgent added in v0.23.0

func (c *MuxClient) SetUserAgent(userAgent string) RESTClient

type Pointer

type Pointer[T any] interface {
	*T
}

Define a constraint for pointer types

type RESTClient

type RESTClient interface {
	Get(ctx context.Context, path string, response interface{}) (int, error)
	Post(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)
	Put(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)
	Delete(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)
	PostJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)
	PutJSON(ctx context.Context, path string, request interface{}, response interface{}, successCode int) (int, error)
	GetJSON(ctx context.Context, path string, response interface{}) (int, error)
	SetTimeout(timeout time.Duration) RESTClient
	SetContentType(contentType string) RESTClient
	SetAccept(accept ...string) RESTClient
	SetUserAgent(userAgent string) RESTClient
	AppendUserAgent(userAgent string) RESTClient
	SetResponseCheck(check func(*http.Response) error) RESTClient
	SetAuthToken(token string) RESTClient
	SetTokenKey(key string) RESTClient
	SetTokenFormat(format string) RESTClient
	SetHeader(key, value string) RESTClient
	DeleteHeader(key string) RESTClient
	ClearHeaders() RESTClient
	GetBaseURL() string
	GetAuthToken() string
	SetBaseUrl(baseURL string) (RESTClient, error)
}

RESTClient interface for both HTTP and Mux clients

func NewMuxClient added in v0.23.0

func NewMuxClient(user *model.User) RESTClient

NewMuxClient creates a client that calls mux directly

type RawClient added in v0.37.0

type RawClient interface {
	DoRaw(ctx context.Context, method string, path string, body io.Reader, size int64, headers map[string]string) (*http.Response, error)
}

RawClient is a client that can send a raw request body with extra headers and hand back the unread response. HTTPClient and MuxClient both are.

type StreamResponseFunc

type StreamResponseFunc func(chunk interface{}) (isDone bool, err error)

type StreamWriter

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

StreamWriter writes chunks using Server-Sent Events

func NewStreamWriter added in v0.19.0

func NewStreamWriter(w http.ResponseWriter, r *http.Request) *StreamWriter

NewStreamWriter creates a new stream writer

func (*StreamWriter) Close

func (sw *StreamWriter) Close() error

Close closes the stream writer

func (*StreamWriter) WriteChunk

func (sw *StreamWriter) WriteChunk(chunk interface{}) error

WriteChunk writes a single chunk as SSE

func (*StreamWriter) WriteEnd

func (sw *StreamWriter) WriteEnd() error

WriteEnd signals the end of the stream

func (*StreamWriter) WriteEvent added in v0.23.0

func (sw *StreamWriter) WriteEvent(eventType string, data any) error

WriteEvent writes an SSE comment event in the format ":eventType:jsonData\n\n" This is used for tool status notifications that standard OpenAI clients ignore

Jump to

Keyboard shortcuts

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