Documentation
¶
Overview ¶
Package gouldian is Go combinator library for building HTTP services. The library is a thin layer of purely functional abstractions to building simple and declarative api implementations in the absence of pattern matching for traditional and serverless applications.
Inspiration ¶
The library is heavily inspired by Scala Finch https://github.com/finagle/finch.
Getting started ¶
Here is minimal "Hello World!" example that matches any HTTP requests to /hello endpoint.
package main
import (
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
"net/http"
)
func main() {
http.ListenAndServe(":8080",
httpd.Serve(hello()),
)
}
func hello() µ.Routable {
return µ.GET(
µ.URI(µ.Path("hello")),
func(ctx *µ.Context) error {
return ø.Status.OK(ø.ContentType.TextPlain, ø.Send("Hello World!"))
},
)
}
See examples folder for advanced use-case.
Next steps ¶
↣ Study Endpoint type and its composition, see User Guide
↣ Check build-in collection of endpoints to deal with HTTP request. See types: HTTP, APIGateway
↣ Endpoint returns one of the outcomes: nil (matched), NoMatch (not my route), Failure (my route, bad input), Output (the response) or error. The Server turns the outcomes into HTTP responses (404, 405, 400, RFC 9457 problems, ...). See Server, Failure, Output, Issue types and MIGRATION-v3.md.
Index ¶
- Constants
- Variables
- func DefaultIssue(issue Issue, cause error) (string, []byte)
- func FromContext[S any](ctx *Context, val *S) error
- func Optics2[T, A, B any](attr ...string) (Lens, Lens)
- func Optics3[T, A, B, C any](attr ...string) (Lens, Lens, Lens)
- func Optics4[T, A, B, C, D any](attr ...string) (Lens, Lens, Lens, Lens)
- func Optics5[T, A, B, C, D, E any](attr ...string) (Lens, Lens, Lens, Lens, Lens)
- func Optics6[T, A, B, C, D, E, F any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens)
- func Optics7[T, A, B, C, D, E, F, G any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens)
- func Optics8[T, A, B, C, D, E, F, G, H any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens)
- func Optics9[T, A, B, C, D, E, F, G, H, I any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens)
- func RegisterCodec[T any](decode func(string) (T, error))
- type CORS
- type Context
- type Endpoint
- func Authorization(f func(string, string) error) Endpoint
- func Body(lens Lens) Endpoint
- func BodyMaybe(lens Lens) Endpoint
- func FMap[A any](f func(*Context, *A) error) Endpoint
- func Header[T MatchableHeaderValues](hdr string, val T) Endpoint
- func HeaderAny(hdr string) Endpoint
- func HeaderMaybe(header string, lens Lens) Endpoint
- func JWT[T Pattern](claim JWTClaim, val T) Endpoint
- func JWTAllOf(claim JWTClaim, vals ...string) Endpoint
- func JWTMaybe(claim JWTClaim, lens Lens) Endpoint
- func JWTOneOf(claim JWTClaim, vals ...string) Endpoint
- func Join(seq ...Endpoint) Endpoint
- func Lenient(e Endpoint) Endpoint
- func Map[A, B any](f func(*Context, *A) (*B, error)) Endpoint
- func Method(verb string) Endpoint
- func Or(seq ...Endpoint) Endpoint
- func Param[T Pattern](key string, val T) Endpoint
- func ParamAny(key string) Endpoint
- func ParamJSON(key string, lens Lens) Endpoint
- func ParamMaybe(key string, lens Lens) Endpoint
- func ParamMaybeJSON(key string, lens Lens) Endpoint
- func Params(lens Lens) Endpoint
- func Trace(name string, e Endpoint) Endpoint
- type Endpoints
- type Failure
- type FieldError
- type Guard
- type HeaderEnumConnection
- type HeaderEnumContent
- func (h HeaderEnumContent) Any(ctx *Context) error
- func (h HeaderEnumContent) ApplicationJSON(ctx *Context) error
- func (h HeaderEnumContent) Form(ctx *Context) error
- func (h HeaderEnumContent) HTML(ctx *Context) error
- func (h HeaderEnumContent) Is(values ...string) Endpoint
- func (h HeaderEnumContent) JSON(ctx *Context) error
- func (h HeaderEnumContent) Text(ctx *Context) error
- func (h HeaderEnumContent) TextHTML(ctx *Context) error
- func (h HeaderEnumContent) TextPlain(ctx *Context) error
- func (h HeaderEnumContent) To(lens Lens) Endpoint
- type HeaderEnumTransferEncoding
- func (h HeaderEnumTransferEncoding) Any(ctx *Context) error
- func (h HeaderEnumTransferEncoding) Chunked(ctx *Context) error
- func (h HeaderEnumTransferEncoding) Identity(ctx *Context) error
- func (h HeaderEnumTransferEncoding) Is(value string) Endpoint
- func (h HeaderEnumTransferEncoding) To(lens Lens) Endpoint
- type HeaderOf
- type Issue
- type IssueHandler
- type IssueRenderer
- type JWTClaim
- type Lens
- type MatchableHeaderValues
- type NoMatch
- type Observer
- type Option
- func WithBodyLimit(n int64) Option
- func WithCORS(cors *CORS) Option
- func WithGuard(guards ...Guard) Option
- func WithIssue(f IssueRenderer) Option
- func WithIssueHandler(f IssueHandler) Option
- func WithLogRoutes(on bool) Option
- func WithLogger(log *slog.Logger) Option
- func WithObserver(observers ...Observer) Option
- func WithRecover(on bool) Option
- func WithTrailingSlash(p TrailingSlash) Option
- type Output
- func (out *Output) AddHeader(header, value string)
- func (out Output) Error() string
- func (out *Output) Free()
- func (out *Output) GetHeader(header string) string
- func (out *Output) SetHeader(header, value string)
- func (out *Output) SetIssue(failure error, title ...string)
- func (out *Output) Unwrap() error
- type Pattern
- type Query
- type ReadableHeaderValues
- type Result
- type Routable
- func ANY(path Routable, arrows ...Endpoint) Routable
- func DELETE(path Routable, arrows ...Endpoint) Routable
- func GET(path Routable, arrows ...Endpoint) Routable
- func HTTP(verb string, path Routable, arrows ...Endpoint) Routable
- func Named(name string, route Routable) Routable
- func PATCH(path Routable, arrows ...Endpoint) Routable
- func POST(path Routable, arrows ...Endpoint) Routable
- func PUT(path Routable, arrows ...Endpoint) Routable
- func URI(segments ...Segment) Routable
- func URIf(uri string, lenses ...Lens) Routable
- type Route
- type Routes
- type Segment
- type Server
- type Source
- type Token
- func (t Token) Bool(claim string) (bool, bool)
- func (t Token) ClientID() string
- func (t Token) Exp() string
- func (t Token) Get(claim string) (any, bool)
- func (t Token) Iss() string
- func (t Token) Jti() string
- func (t Token) Number(claim string) (float64, bool)
- func (t Token) Scope() string
- func (t Token) String(claim string) string
- func (t Token) Strings(claim string) []string
- func (t Token) Sub() string
- func (t Token) Username() string
- type TrailingSlash
Examples ¶
Constants ¶
const ( Accept = HeaderEnumContent("Accept") AcceptCharset = HeaderOf[string]("Accept-Charset") AcceptEncoding = HeaderOf[string]("Accept-Encoding") AcceptLanguage = HeaderOf[string]("Accept-Language") CacheControl = HeaderOf[string]("Cache-Control") Connection = HeaderEnumConnection("Connection") ContentEncoding = HeaderOf[string]("Content-Encoding") ContentLength = HeaderOf[int]("Content-Length") ContentType = HeaderEnumContent("Content-Type") Cookie = HeaderOf[string]("Cookie") Date = HeaderOf[time.Time]("Date") From = HeaderOf[string]("From") Host = HeaderOf[string]("Host") IfMatch = HeaderOf[string]("If-Match") IfModifiedSince = HeaderOf[time.Time]("If-Modified-Since") IfNoneMatch = HeaderOf[string]("If-None-Match") IfRange = HeaderOf[string]("If-Range") IfUnmodifiedSince = HeaderOf[time.Time]("If-Unmodified-Since") Origin = HeaderOf[string]("Origin") Range = HeaderOf[string]("Range") Referer = HeaderOf[string]("Referer") TransferEncoding = HeaderEnumTransferEncoding("Transfer-Encoding") UserAgent = HeaderOf[string]("User-Agent") Upgrade = HeaderOf[string]("Upgrade") )
List of supported HTTP header constants https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
const (
// Any constant matches any term
Any = "_"
)
const DefaultBodyLimit int64 = 6 << 20
DefaultBodyLimit is the default limit of the request body (6 MiB, the payload limit of AWS Lambda).
const Version = "gouldian/v3.1.0"
Version of the library
Variables ¶
var ( ErrBodyRequired = errors.New("body is required") ErrBodyTooLarge = errors.New("body is too large") ErrMethod = errors.New("method is not allowed") )
Common failures
var ErrNoMatch error = NoMatchAny
ErrNoMatch is the generic NoMatch outcome
Functions ¶
func DefaultIssue ¶
DefaultIssue renders RFC 9457 `application/problem+json`
func FromContext ¶
FromContext decodes the context into structure
func Optics2 ¶
Optics2 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics3 ¶
Optics3 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics4 ¶
Optics4 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics5 ¶
Optics5 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics6 ¶
Optics6 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics7 ¶
Optics7 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics8 ¶
func Optics8[T, A, B, C, D, E, F, G, H any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens)
Optics8 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func Optics9 ¶
func Optics9[T, A, B, C, D, E, F, G, H, I any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens, Lens)
Optics9 unfold attribute(s) of type T. If the names of attributes are not defined, the fields are discovered by types. The n-th occurrence of the type binds the n-th field of the type.
func RegisterCodec ¶
RegisterCodec registers a decoder for the type T. The decoder is used by all lenses created after the registration.
Types ¶
type CORS ¶
type CORS struct {
// Origins is allow-list of origins, "*" allows any origin (but never with Credentials)
Origins []string
// Methods allowed by preflight. All methods of the resource if empty.
Methods []string
// Headers allowed by preflight. It reflects requested headers if empty.
Headers []string
// Expose lists headers exposed to the browser
Expose []string
// MaxAge of preflight cache
MaxAge time.Duration
// Credentials allows cookies and authorization
Credentials bool
}
CORS configuration of the server. CORS is disabled by default.
type Context ¶
type Context struct {
context.Context
Request *http.Request
// RequestID is the identity of the request assigned by the platform
RequestID string
JWT Token
// contains filtered or unexported fields
}
Context of HTTP request. The context accumulates matched terms of HTTP and passes it to destination function. It embeds context.Context of the caller (http.Request, AWS Lambda invocation), so the cancellation, the deadline and the trace identity are available to the handlers.
func NewContext ¶
NewContext create a new context for HTTP request
func (*Context) Put ¶
Put injects value to the context. A value that cannot be decoded is a Failure.
func (*Context) Route ¶ added in v3.1.0
Route is the route that took the request: its endpoint accepted the request, or failed it. It is nil if no route did (404, 405, ...) or the request was rejected by a guard. The value is shared, do not modify it.
func (*Context) Set ¶ added in v3.1.0
Set attaches the attribute to the request, Value returns it. Use it to pass facts between guards, endpoints and observers: the principal admitted by the guard, the operation and its outcome for the access log, etc. Attributes live until the context is released. Keys follow the rules of context.WithValue: use an unexported type, not a string. Set is not safe for concurrent use, call it from the goroutine of the request.
type Endpoint ¶
Endpoint is a composable function that abstract HTTP endpoint. The function takes HTTP request and returns value of some type: `Context => Output`.
↣ `Context` is a wrapper over HTTP request with additional context.
↣ `Output` is sum type that represents the outcome of the endpoint:
nil matched, continue the product
NoMatch not my route, Or tries the next endpoint (zero allocation)
*Failure my route, bad input (malformed value, empty body, ...),
terminal, Or does not try other endpoints
*Output terminal response of the handler
error any other error, it is 500
Any `Endpoint A` can be composed with `Endpoint B` into new `Endpoint C`. It supports two combinators: and-then, or-else.
↣ Use `and-then` to build product Endpoint. The product type matches Input if each composed function successfully matches it.
↣ Use `or-else` to build co-product Endpoint. The co-product is also known as sum-type matches first successful function. A branch that does not match leaves no traces in the context.
func Authorization ¶
Authorization defines Endpoints that simplify validation of credentials/tokens supplied within the request
e := µ.GET( µ.Authorization(func(string, string) error { ... }) )
e(mock.Input(mock.Header("Authorization", "Basic foo"))) == nil
e(mock.Input(mock.Header("Authorization", "Basic bar"))) != nil
func Body ¶
Body decodes HTTP request body and lifts it to the structure. The body is read once and shared by all endpoints of the request, so several lenses (e.g. raw bytes and typed struct) can read the same body.
An empty body is Failure (400, "body is required"). A body over the limit of the server is Failure (413). A body that cannot be decoded by the lens is Failure (400) with JSON pointer to the invalid value.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
type payload struct {
Name string `json:"name"`
}
type request struct {
Payload payload `content:"json,strict"`
}
post := µ.POST(
µ.URI(µ.Path("users")),
µ.ContentType.JSON,
µ.Body(µ.Optics1[request, payload]()),
µ.FMap(func(ctx *µ.Context, req *request) error {
return ø.Status.Created(ø.Send(req.Payload.Name))
}),
)
api := httpd.Serve(post)
json := []string{"Content-Type", "application/json"}
do(api, "POST", "/users", `{"name":"joe"}`, json...)
do(api, "POST", "/users", "", json...)
do(api, "POST", "/users", `{"name":"joe","unknown":1}`, json...)
do(api, "POST", "/users", `{"name":"joe"}`, "Content-Type", "text/plain")
}
Output: 201 joe 400 application/problem+json {"type":"about:blank","title":"Bad Request","status":400,"detail":"body is required","instance":"/users"} 400 application/problem+json {"type":"about:blank","title":"Bad Request","status":400,"detail":"body /unknown: json: unknown field \"unknown\"","instance":"/users","errors":[{"source":"body","pointer":"/unknown","detail":"json: unknown field \"unknown\""}]} 415 application/problem+json {"type":"about:blank","title":"Unsupported Media Type","status":415,"instance":"/users"}
func FMap ¶
FMap applies clojure to matched HTTP request, taking the execution context as the input to closure
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
type greeting struct {
Name string
Times int
}
func main() {
name, times := µ.Optics2[greeting, string, int]("Name", "Times")
hello := µ.GET(
µ.URI(µ.Path("hello"), µ.Path(name)),
µ.ParamMaybe("times", times),
µ.FMap(func(ctx *µ.Context, req *greeting) error {
return ø.Status.OK(
ø.ContentType.TextPlain,
ø.Send(fmt.Sprintf("Hello %s x%d", req.Name, req.Times)),
)
}),
)
api := httpd.Serve(hello)
do(api, "GET", "/hello/Joe?times=3", "")
// a malformed value is not "no match", it is 400 that names the parameter
do(api, "GET", "/hello/Joe?times=many", "")
}
Output: 200 text/plain Hello Joe x3 400 application/problem+json {"type":"about:blank","title":"Bad Request","status":400,"detail":"query times: strconv.Atoi: parsing \"many\": invalid syntax","instance":"/hello/Joe","errors":[{"source":"query","pointer":"times","detail":"strconv.Atoi: parsing \"many\": invalid syntax"}]}
func Header ¶
func Header[T MatchableHeaderValues](hdr string, val T) Endpoint
Header combinator defines primitives to match Headers of HTTP requests. A literal is matched by exact (case-insensitive) value of the header.
endpoint := µ.GET(
µ.Header("X-Foo", "Bar"),
)
endpoint(
mock.Input(
mock.Header("X-Foo", "Bar")
)
) == nil
An absent header or differing literal is NoMatch. A header that is present but cannot be decoded by the lens is Failure (400).
func HeaderAny ¶
HeaderAny is a wildcard matcher of header. It fails if header is not defined.
e := µ.GET( µ.HeaderAny("X-Foo") )
e(mock.Input(mock.Header("X-Foo", "Bar"))) == nil
e(mock.Input(mock.Header("X-Foo", "Baz"))) == nil
e(mock.Input()) != nil
func HeaderMaybe ¶
HeaderMaybe matches header value to the request context. It uses lens abstraction to decode HTTP header into Golang type. The Endpoint matches if the header is not defined. A header that is present but cannot be decoded is Failure.
type myT struct{ Val string }
x := µ.Optics1[myT, string]()
e := µ.GET(µ.HeaderMaybe("X-Foo", x))
e(mock.Input(mock.Header("X-Foo", "Bar"))) == nil
func JWT ¶
JWT combinator defines primitives to match JWT token in the HTTP requests.
endpoint := µ.GET(
µ.JWT(µ.Token.Username, "joedoe"),
)
endpoint(
mock.Input(
mock.JWT(µ.Token{"username": "joedoe"})
)
) == nil
func JWTAllOf ¶
JWTAllOf matches a key of JWT if it contains all of the tokens. The claim is a space-delimited list (e.g. OAuth scope), tokens are compared as whole words, `ro` does not match `prod:write`.
µ.GET( µ.JWTAllOf(µ.JWT.Scope, "ro", "rw") )
func JWTMaybe ¶
JWTMaybe matches key of JWT to the request context. It uses lens abstraction to decode value into Golang type. The Endpoint does not fail if the claim is absent, a malformed claim is a failure. See optics.Lens type for details.
type MyT struct{ Username string }
username := µ.Optics1[MyT, string]()
e := µ.GET( µ.JWTMaybe(µ.JWT.Sub).Maybe(username) )
e(mock.Input(mock.JWT(µ.JWT{"username": "joedoe"}))) == nil
func JWTOneOf ¶
JWTOneOf matches a key of JWT if it contains one of the tokens. The claim is a space-delimited list (e.g. OAuth scope), tokens are compared as whole words, `ro` does not match `prod:write`.
µ.GET( µ.JWTOneOf(µ.JWT.Scope, "ro", "rw") )
func Lenient ¶
Lenient turns a Failure of the endpoint into NoMatch. It brings back the behaviour of v2: a malformed value is yet another "not my route".
func Map ¶
Map applies clojure to matched HTTP request, taking the execution context and matched parameters as the input to closure. The output is always returned as JSON.
func Method ¶
Method is an endpoint to match HTTP verb request. Routes built by GET, POST, etc. carry the verb as metadata, use the endpoint only to constrain a request inside the route (e.g. ANY).
func Param ¶
Param combinator defines primitives to match query param in the HTTP requests.
endpoint := µ.GET(
µ.Param("foo", "bar"),
)
endpoint(
mock.Input(
mock.URL("/?foo=bar")
)
) == nil
An absent param or differing literal is NoMatch. A param that is present but cannot be decoded by the lens is Failure (400).
func ParamAny ¶
ParamAny is a wildcard matcher of param key. It fails if key is not defined.
e := µ.GET( µ.ParamAny("foo") )
e(mock.Input(mock.URL("/?foo"))) == nil
e(mock.Input(mock.URL("/?foo=bar"))) == nil
e(mock.Input(mock.URL("/?foo=baz"))) == nil
e(mock.Input()) != nil
func ParamJSON ¶
ParamJSON matches a param key to struct. It assumes that key holds JSON value as url encoded string
func ParamMaybe ¶
ParamMaybe matches param value to the request context. It uses lens abstraction to decode value into Golang type. The Endpoint matches if the param is not defined. A param that is present but cannot be decoded to the target type is Failure.
type myT struct{ Val string }
x := µ.Optics1[myT, string]()
e := µ.GET( µ.ParamMaybe("foo", x) )
e(mock.Input(mock.URL("/?foo=bar"))) == nil
e(mock.Input(mock.URL("/?foo"))) == nil
e(mock.Input(mock.URL("/"))) == nil
func ParamMaybeJSON ¶
ParamMaybeJSON matches a param key to closed struct. It assumes that key holds JSON value as url encoded string. It does not fail if key is not defined, a malformed value is Failure.
func Params ¶
Params lifts all Query parameters to struct
type MyRequest struct {
Params MyType `content:"form"`
}
var params = µ.Optics1[MyRequest, MyType]()
µ.GET(µ.Params(params))
type Endpoints ¶
type Endpoints []Endpoint
Endpoints is sequence of Endpoints
type Failure ¶
type Failure struct {
// HTTP Status, 400 by default
Status int
// Source of the input, the Key identifies the value within the source:
// name of param, header, JSON pointer of body, etc.
Source Source
Key string
// Cause of the failure
Err error
// Extra headers of the response (e.g. Allow for 405)
Header http.Header
}
Failure is returned by Endpoint if the request is routed to the endpoint but the input is invalid: a value is present but malformed (decode error), a body is empty or exceeds the limit. It is the "my route, bad input" outcome. Failure is terminal, coproduct (Or) does not try other endpoints. The server converts the failure to an Issue (RFC 9457).
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
type request struct{ Limit int }
limit := µ.Optics1[request, int]()
get := µ.GET(
µ.URI(µ.Path("items")),
µ.ParamMaybe("limit", limit),
func(ctx *µ.Context) error {
// the application fails with the cause, the server logs the cause
// and renders the problem, the cause of 5xx is never exposed
return ø.Status.Forbidden(ø.Error(fmt.Errorf("items are not yours")))
},
)
do(httpd.Serve(get), "GET", "/items", "")
}
Output: 403 application/problem+json {"type":"about:blank","title":"Forbidden","status":403,"detail":"items are not yours","instance":"/items"}
type FieldError ¶
type FieldError struct {
// Source of the value: path, query, header, body, jwt
Source string `json:"source,omitempty"`
// Pointer to the value: RFC 6901 JSON pointer for the body, the name of
// query param or header otherwise.
Pointer string `json:"pointer,omitempty"`
Detail string `json:"detail"`
}
FieldError points to the invalid value
type Guard ¶ added in v3.1.0
Guard admits the request before routing. A nil admits the request, any other outcome is the response, as if an endpoint returned it (e.g. a *Failure, an *Output, an error). The rejection is rendered through the issue of the server, the router is never consulted, so a client who is not admitted cannot tell known routes from unknown ones.
Guards run for every request, including CORS preflight (OPTIONS): a guard that authorizes requests must admit preflight if CORS is enabled. Guards may set attributes of the context (Context.Set), they shall not bind lenses.
type HeaderEnumConnection ¶
type HeaderEnumConnection string
Type of HTTP Header, Connection enumeration
const Connection = HeaderEnumConnection("Connection")
µ.Connection.KeepAlive
func (HeaderEnumConnection) Any ¶
func (h HeaderEnumConnection) Any(ctx *Context) error
Matches header to any value
func (HeaderEnumConnection) Close ¶
func (h HeaderEnumConnection) Close(ctx *Context) error
Close defines header `???: close`
func (HeaderEnumConnection) Is ¶
func (h HeaderEnumConnection) Is(value string) Endpoint
Matches value of HTTP header
func (HeaderEnumConnection) KeepAlive ¶
func (h HeaderEnumConnection) KeepAlive(ctx *Context) error
KeepAlive defines header `???: keep-alive`
func (HeaderEnumConnection) To ¶
func (h HeaderEnumConnection) To(lens Lens) Endpoint
Matches value of HTTP header
type HeaderEnumContent ¶
type HeaderEnumContent string
Type of HTTP Header, Content-Type and Accept enumeration
const ContentType = HeaderEnumContent("Content-Type")
µ.ContentType.JSON
The Content-Type matches by media type, parameters (charset) are ignored, the comparison is case-insensitive. A mismatch is NoMatchContentType, the server responds with 415 if no other endpoint matches.
The Accept header is negotiated: comma separated list, q-values, \*/\* and type/\* are supported. A missing header accepts anything. A mismatch is NoMatchAccept, the server responds with 406 if no other endpoint matches.
func (HeaderEnumContent) Any ¶
func (h HeaderEnumContent) Any(ctx *Context) error
Matches header to any value
func (HeaderEnumContent) ApplicationJSON ¶
func (h HeaderEnumContent) ApplicationJSON(ctx *Context) error
ApplicationJSON defines header `???: application/json`
func (HeaderEnumContent) Form ¶
func (h HeaderEnumContent) Form(ctx *Context) error
Form defined Header `???: application/x-www-form-urlencoded`
func (HeaderEnumContent) HTML ¶
func (h HeaderEnumContent) HTML(ctx *Context) error
HTML defined Header `???: text/html`
func (HeaderEnumContent) Is ¶
func (h HeaderEnumContent) Is(values ...string) Endpoint
Is matches the header to one of media types
func (HeaderEnumContent) JSON ¶
func (h HeaderEnumContent) JSON(ctx *Context) error
JSON defines header `???: application/json`
func (HeaderEnumContent) Text ¶
func (h HeaderEnumContent) Text(ctx *Context) error
Text defined Header `???: text/plain`
func (HeaderEnumContent) TextHTML ¶
func (h HeaderEnumContent) TextHTML(ctx *Context) error
TextHTML defined Header `???: text/html`
func (HeaderEnumContent) TextPlain ¶
func (h HeaderEnumContent) TextPlain(ctx *Context) error
TextPlain defined Header `???: text/plain`
func (HeaderEnumContent) To ¶
func (h HeaderEnumContent) To(lens Lens) Endpoint
Matches value of HTTP header
type HeaderEnumTransferEncoding ¶
type HeaderEnumTransferEncoding string
Type of HTTP Header, Transfer-Encoding enumeration
const TransferEncoding = HeaderEnumTransferEncoding("Transfer-Encoding")
µ.TransferEncoding.Chunked
func (HeaderEnumTransferEncoding) Any ¶
func (h HeaderEnumTransferEncoding) Any(ctx *Context) error
Matches header to any value
func (HeaderEnumTransferEncoding) Chunked ¶
func (h HeaderEnumTransferEncoding) Chunked(ctx *Context) error
Chunked defines header `Transfer-Encoding: chunked`
func (HeaderEnumTransferEncoding) Identity ¶
func (h HeaderEnumTransferEncoding) Identity(ctx *Context) error
Identity defines header `Transfer-Encoding: identity`
func (HeaderEnumTransferEncoding) Is ¶
func (h HeaderEnumTransferEncoding) Is(value string) Endpoint
Matches value of HTTP header
func (HeaderEnumTransferEncoding) To ¶
func (h HeaderEnumTransferEncoding) To(lens Lens) Endpoint
Matches value of HTTP header
type HeaderOf ¶
type HeaderOf[T MatchableHeaderValues] string
Internal type
type Issue ¶
type Issue struct {
// Type is URI reference that identifies the problem, about:blank by default
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
// Instance is the request path
Instance string `json:"instance,omitempty"`
Errors []FieldError `json:"errors,omitempty"`
}
Issue implements RFC 9457: Problem Details for HTTP APIs
type IssueHandler ¶ added in v3.1.0
IssueHandler renders the failure into the output. Unlike IssueRenderer, it owns the whole response: it may change the status, set headers (e.g. Retry-After, WWW-Authenticate) and the body, and it sees the context of the request (RequestID, JWT, attributes). The issue is the default description of the failure, the cause is the error of the endpoint (nil for 404, 405, 406, 415).
type IssueRenderer ¶
IssueRenderer converts the failure to the body of response
type Lens ¶
Lens is a setter of decoded HTTP value to a field of struct. The decoder is chosen once when the lens is constructed:
- field tag `content:"json"`, `content:"json,strict"`, `content:"form"`;
- decoder registered by RegisterCodec;
- encoding.TextUnmarshaler (the type validates itself);
- string, bool, int*, uint*, float*, time.Duration, []byte (raw), slices of them (repeated param or tag `sep:","`), pointers;
- struct is JSON by default.
Unsupported type panics when the lens is constructed (at start-up).
func At ¶
At builds a lens for the field of struct T. It is a type-safe-enough alternative to OpticsN if the lens is required inline. The name of the field is checked when the lens is constructed, an unknown field panics at start-up.
µ.POST(µ.URI(µ.Path("ds"), µ.Path(µ.At[reqCreate]("Class"))))
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
type create struct{ Class string }
post := µ.POST(
µ.URI(µ.Path("ds"), µ.Path(µ.At[create]("Class"))),
µ.FMap(func(ctx *µ.Context, req *create) error {
return ø.Status.Created(ø.Send(req.Class))
}),
)
do(httpd.Serve(post), "POST", "/ds/books", "")
}
Output: 201 books
type MatchableHeaderValues ¶
type MatchableHeaderValues interface {
ReadableHeaderValues | Lens
}
type NoMatch ¶
type NoMatch uint8
NoMatch is returned by Endpoint if Context is not matched: "not my route". The value is a reason code, it costs nothing to carry (no allocations). Coproduct (Or) tries the next endpoint on NoMatch. If no endpoint matches then the most specific reason is reported (the one with the largest code).
const ( NoMatchAny NoMatch = iota + 1 NoMatchPath NoMatchMethod NoMatchHeader NoMatchParam NoMatchJWT NoMatchBody // content negotiation, a service responds with 406 or 415 if // no other endpoint matches the request NoMatchAccept NoMatchContentType )
Reasons of NoMatch, ordered from least to most specific.
type Observer ¶ added in v3.1.0
Observer sees every request once it is served: the final response (rendered issue, CORS headers), the route that took it (Context.Route, nil if none did), the attributes of the context and the time of dispatch. The observer must not keep the context or the output, both are released once the response is sent.
type Option ¶
type Option func(*Server)
Option of the server
func WithBodyLimit ¶
WithBodyLimit sets the limit of request body (413 if exceeded). The default is 6 MiB, 0 disables the limit.
func WithGuard ¶ added in v3.1.0
WithGuard appends guards to the server, they run in the given order.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
type principal struct{}
api := µ.NewServer(
// the guard admits the request before routing, a rejected client
// cannot tell known routes from unknown ones
µ.WithGuard(func(ctx *µ.Context) error {
key := ctx.Request.Header.Get("X-Api-Key")
if key == "" {
return ø.Status.Unauthorized(ø.Error(fmt.Errorf("api key is required")))
}
ctx.Set(principal{}, key)
return nil
}),
).Mount(
µ.GET(µ.URI(µ.Path("me")), func(ctx *µ.Context) error {
return ø.Status.OK(ø.ContentType.TextPlain, ø.Send(ctx.Value(principal{}).(string)))
}),
)
h := httpd.Handler(api)
do(h, "GET", "/me", "", "X-Api-Key", "joe")
do(h, "GET", "/unknown", "")
}
Output: 200 text/plain joe 401 application/problem+json {"type":"about:blank","title":"Unauthorized","status":401,"detail":"api key is required","instance":"/unknown"}
func WithIssue ¶
func WithIssue(f IssueRenderer) Option
WithIssue sets the renderer of failures, the application owns the shape of problem. The default is RFC 9457 `application/problem+json`.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
api := µ.NewServer(
µ.WithIssue(func(issue µ.Issue, cause error) (string, []byte) {
return "application/json", []byte(fmt.Sprintf(`{"code":"E%d"}`, issue.Status))
}),
)
do(httpd.Handler(api), "GET", "/", "")
}
Output: 404 application/json {"code":"E404"}
func WithIssueHandler ¶ added in v3.1.0
func WithIssueHandler(f IssueHandler) Option
WithIssueHandler sets the handler of failures, it takes precedence over WithIssue. Every failure is rendered by it: the outcome of endpoints, the rejection of a guard and the responses of the router itself.
Example ¶
package main
import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"time"
µ "github.com/fogfish/gouldian/v3"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
// errBusy is a failure of the domain, it knows its own status
type errBusy struct{ retry time.Duration }
func (e errBusy) Error() string { return "busy" }
func main() {
api := µ.NewServer(
µ.WithLogger(slog.New(slog.DiscardHandler)),
// the handler owns the response of every failure: the status, the
// headers and the body
µ.WithIssueHandler(func(ctx *µ.Context, issue µ.Issue, cause error, out *µ.Output) {
code := strings.ReplaceAll(strings.ToLower(issue.Title), " ", "_")
var busy errBusy
if errors.As(cause, &busy) {
out.Status, code = http.StatusServiceUnavailable, "busy"
out.SetHeader("Retry-After", fmt.Sprint(busy.retry.Seconds()))
}
out.SetHeader("Content-Type", "application/json")
out.Body = []byte(fmt.Sprintf(`{"code":"%s"}`, code))
}),
).Mount(
µ.GET(µ.URI(µ.Path("things")), func(*µ.Context) error {
return errBusy{retry: 5 * time.Second}
}),
)
h := httpd.Handler(api)
do(h, "GET", "/things", "")
do(h, "GET", "/unknown", "")
}
Output: 503 application/json {"code":"busy"} 404 application/json {"code":"not_found"}
func WithLogRoutes ¶
WithLogRoutes enables the log of configured routes (off by default). Mount logs, at info level, one record with all mounted routes as "METHOD /path", where ":" is a variable, "_" any segment and "*" the rest of the path.
level=INFO msg="routes mounted" count=2 routes="[GET /users/: POST /users]"
func WithLogger ¶
WithLogger sets the logger, slog.Default() otherwise. 5xx are logged at error level, 4xx at debug level. Only method and path are logged, never the query string.
func WithObserver ¶ added in v3.1.0
WithObserver appends observers to the server (access logs, metrics, traces), they run in the given order.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"time"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
api := µ.NewServer(
// the observer sees the final response and the route that took it
µ.WithObserver(func(ctx *µ.Context, out *µ.Output, elapsed time.Duration) {
route := "-"
if r := ctx.Route(); r != nil {
route = r.Name
}
fmt.Printf("access: %s %d\n", route, out.Status)
}),
).Mount(
µ.Named("things.list",
µ.GET(µ.URI(µ.Path("things")), func(*µ.Context) error { return ø.Status.OK(ø.Send("list")) }),
),
)
h := httpd.Handler(api)
do(h, "GET", "/things", "")
do(h, "GET", "/unknown", "")
}
Output: access: things.list 200 200 list access: - 404 404 application/problem+json {"type":"about:blank","title":"Not Found","status":404,"instance":"/unknown"}
func WithRecover ¶
WithRecover enables recovery from panics, it is on by default.
func WithTrailingSlash ¶
func WithTrailingSlash(p TrailingSlash) Option
WithTrailingSlash sets the policy of trailing slash, Strict by default.
type Output ¶
type Output struct {
Status int
Headers []struct{ Header, Value string }
Body []byte
// Failure is the cause of the failed request. The server logs it and,
// if the Body is empty, renders it as Issue.
Failure error
// Title of the Issue
Title string
// contains filtered or unexported fields
}
Output is the HTTP response produced by the handler. Outputs created by NewOutput are pooled and released by the server, so never keep or share them: construct a literal (&µ.Output{...}) if the value is a global constant.
func (*Output) AddHeader ¶
AddHeader appends the header, existing values are kept (e.g. Set-Cookie).
type Result ¶
Result is a composable function that abstract results of HTTP endpoint. The function takes instance of HTTP output and mutates its value
return µ.Status.OK( µ.WithHeader(headers.ContentType, headers.ApplicationJson), µ.WithJSON(value), )
type Routable ¶
type Routable func() Route
Routable is a lazy route, see URI, GET, POST, ...
func ANY ¶
ANY composes Endpoints into Routable that matches HTTP any request.
e := µ.ANY(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
func DELETE ¶
DELETE composes Endpoints into Routable that matches HTTP DELETE request.
e := µ.DELETE(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
func GET ¶
GET composes Endpoints into Routable that matches HTTP GET request.
e := µ.GET(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
hello := µ.GET(
µ.URI(µ.Path("hello")),
func(ctx *µ.Context) error {
return ø.Status.OK(
ø.ContentType.TextPlain,
ø.Send("Hello World!"),
)
},
)
api := httpd.Serve(hello)
do(api, "GET", "/hello", "")
}
Output: 200 text/plain Hello World!
func HTTP ¶
HTTP composes Endpoints into Routable. The verb is the routing metadata, the server responds with 405 if the path is known but not the verb.
func Named ¶ added in v3.1.0
Named gives the name to the route. The server exposes the route that took the request (Context.Route) to observers, so the name identifies the operation in logs and metrics, without parsing the path.
µ.Named("user.get", µ.GET(µ.URI(µ.Path("users"), µ.Path(id)), ...))
func PATCH ¶
PATCH composes Endpoints into Routable that matches HTTP PATCH request.
e := µ.PATCH(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
func POST ¶
POST composes Endpoints into Routable that matches HTTP POST request.
e := µ.POST(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
func PUT ¶
PUT composes Endpoints into Routable that matches HTTP PUT request.
e := µ.PUT(
µ.URI(µ.Path("foo"), µ.Path("bar")),
...
)
func URI ¶
URI is an endpoint to match URL of HTTP request. The function takes a sequence of segment patterns as input. These patterns are either literals or lenses, where each term corresponds to the path segment. The function do not match if length of path is not equal to the length of pattern or segment do not match to pattern
e := µ.GET( µ.URI(µ.Path("foo")) )
e(mock.Input(mock.URL("/foo"))) == nil
e(mock.Input(mock.URL("/bar"))) != nil
func URIf ¶
URIf builds Routable from a URI pattern, the "f" is for "format": the pattern string is followed by the lenses it binds, like Printf. It is the string form of URI. The syntax is a subset of Go 1.22 http.ServeMux patterns (braces, not % verbs), extended with query parameters (RFC 6570).
µ.GET(
µ.URIf("/users/{id}/files/{path...}{?limit,q}", lID, lPath, lLimit, lQ),
)
↣ `{name}` matches a path segment, it is bound to the next lens;
↣ `{name...}` matches the rest of the path (the last segment only);
↣ `{_}` or `{}` matches any segment without binding;
↣ `{?a,b}` optional query parameters, each is bound to the next lens. A param that is not defined is ignored, a malformed one is Failure (see ParamMaybe).
Literals are matched as is. The pattern is checked when it is constructed: the number of placeholders must be equal to the number of lenses, otherwise it panics with the pattern in the message.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
type file struct {
User string
Path string
}
user, path := µ.Optics2[file, string, string]("User", "Path")
get := µ.GET(
µ.URIf("/users/{user}/files/{path...}", user, path),
µ.FMap(func(ctx *µ.Context, req *file) error {
return ø.Status.OK(ø.Send(req.User + ":" + req.Path))
}),
)
do(httpd.Serve(get), "GET", "/users/joe/files/a/b.txt", "")
}
Output: 200 joe:a/b.txt
type Route ¶
type Route struct {
// Name of the route, an identity of the operation for logs and metrics,
// see Named. Empty by default.
Name string
// Method of HTTP request (GET, POST, ...), Any matches every verb
Method string
// Path is a sequence of segments: literal, ":" for a variable captured
// by a lens, "_" for any segment, "*" for the rest of the path.
Path []string
Endpoint Endpoint
}
Route is endpoint with routing metadata: HTTP verb, path and the endpoint itself. The metadata allows the server to distinguish "no such resource" (404) from "no such method" (405) and to respond to OPTIONS requests.
type Routes ¶
type Routes struct {
// contains filtered or unexported fields
}
Routes is a routing table. It is built once and it is safe for concurrent use.
type Segment ¶
type Segment struct {
// contains filtered or unexported fields
}
Segment union type, make URI type safe
func Path ¶
Path is an endpoint to match a single URL segment of HTTP request. The function takes a path pattern as arguments. The pattern is either literal or lens. The function do not match if segment do not match to pattern
e := µ.GET( µ.URI(µ.Path("foo")) )
e(mock.Input(mock.URL("/foo"))) == nil
e(mock.Input(mock.URL("/bar"))) != nil
A segment that cannot be decoded by the lens does not match the route, it allows to overload the path (/user/:id by int and by string).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the single place of rules that turns outcomes of endpoints into HTTP responses. It is shared by all adapters (httpd, apigateway, ...):
nil 204 No Content *Output as is *Failure 400 (or the status of failure) Issue NoMatch 404, 405 (Allow), 406, 415; OPTIONS and HEAD are derived error 500, the cause is logged but never exposed panic 500, recovered, the stack is logged
The lifecycle of a request is
guards → routes → issue → log, CORS → observers
the guards admit the request before routing (WithGuard), the issue of a failure is rendered by WithIssue or WithIssueHandler, the observers see the final response (WithObserver).
func NewServer ¶
NewServer creates the server
Example ¶
package main
import (
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
µ "github.com/fogfish/gouldian/v3"
ø "github.com/fogfish/gouldian/v3/output"
"github.com/fogfish/gouldian/v3/server/httpd"
)
// do sends the request through the server, the way a client does
func do(api http.Handler, method, target, body string, headers ...string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
res := w.Result()
buf, _ := io.ReadAll(res.Body)
fmt.Printf("%d %s %s\n", res.StatusCode, res.Header.Get("Content-Type"), buf)
}
func main() {
api := µ.NewServer(
µ.WithLogger(slog.New(slog.DiscardHandler)),
µ.WithBodyLimit(1<<20),
µ.WithTrailingSlash(µ.Ignore),
).Mount(
µ.GET(µ.URI(µ.Path("things")), func(*µ.Context) error { return ø.Status.OK(ø.Send("list")) }),
µ.POST(µ.URI(µ.Path("things")), func(*µ.Context) error { return ø.Status.Created() }),
)
h := httpd.Handler(api)
do(h, "GET", "/things/", "")
do(h, "DELETE", "/things", "")
do(h, "GET", "/unknown", "")
}
Output: 200 list 405 application/problem+json {"type":"about:blank","title":"Method Not Allowed","status":405,"instance":"/things"} 404 application/problem+json {"type":"about:blank","title":"Not Found","status":404,"instance":"/unknown"}
func (*Server) Dispatch ¶
Dispatch executes the request. It never returns nil, the output must be released with Output.Free once it is sent.
func (*Server) NewContext ¶
NewContext creates (from the pool) the context of the request. The context of the caller (http.Request, Lambda invocation) is propagated to handlers. The context must be released by Release.
type Token ¶
Token is a container for claims of access token. The claims keep the type they have in the token (string, number, bool, array, object). Use typed accessors to read them.
func NewToken ¶
NewToken creates access token object from claims. It never panics, the claims keep their types. Null claims are ignored.
func (Token) String ¶
String returns claim as a string. Numbers and booleans are converted to their string form (no exponent), array of strings is joined with space (e.g. scopes). Objects and null are empty.
type TrailingSlash ¶
type TrailingSlash uint8
TrailingSlash is the policy of /path/ vs /path
const ( // Strict (default) treats /path/ and /path as different resources Strict TrailingSlash = iota // Redirect responds to /path/ with 308 to /path Redirect // Ignore removes trailing slash before routing Ignore )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
echo
command
|
|
|
headers
command
|
|
|
helloworld
command
|
|
|
internal/exampletest
Package exampletest runs examples through the HTTP adapters (net/http and AWS API Gateway HTTP API payload 2.0).
|
Package exampletest runs examples through the HTTP adapters (net/http and AWS API Gateway HTTP API payload 2.0). |
|
methods
command
|
|
|
params
command
|
|
|
paths
command
|
|
|
payloads
command
|
|
|
internal
|
|
|
media
Package media helps adapters to serialize responses
|
Package media helps adapters to serialize responses |
|
optics
Package optics is an internal, it implements lenses that bind strings received by HTTP request to fields of Go struct.
|
Package optics is an internal, it implements lenses that bind strings received by HTTP request to fields of Go struct. |
|
server
|
|
|
aws/apigateway
Package apigateway adapts the gouldian server to AWS API Gateway (REST API, payload format 1.0).
|
Package apigateway adapts the gouldian server to AWS API Gateway (REST API, payload format 1.0). |
|
aws/apigatewayv2
Package apigatewayv2 adapts the gouldian server to AWS API Gateway HTTP API and Lambda Function URL (payload format 2.0).
|
Package apigatewayv2 adapts the gouldian server to AWS API Gateway HTTP API and Lambda Function URL (payload format 2.0). |
|
httpd
Package httpd adapts the gouldian server to net/http
|
Package httpd adapts the gouldian server to net/http |