gouldian

package module
v3.1.0 Latest Latest
Warning

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

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

README

µ-Gouldian

A typed, declarative HTTP router for Go that runs the same code on net/http and AWS Lambda. 87 ns per request on a 203-route API, zero allocations, within 1.4× of the fastest router, while binding parameters into structs.

You don't pay for correctness: 404/405/406/415, RFC 9457 problems and safe defaults are built in.


The library is a thin layer of purely functional abstractions to build HTTP services. In the contrast with other HTTP routers, the library resolves a challenge of building simple and declarative api implementations in the absence of pattern matching at Golang. The library also support opaque migration of HTTP service between traditional, containers and serverless environments.

User Guide | Hello World | Other Examples | Benchmark

Inspiration

Microservices have become a design style to evolve system architecture in parallel, implement stable and consistent interfaces within distributed system. An expressive language is required to design the manifold of network interfaces. A pure functional languages fits very well to express communication behavior due they rich techniques to hide the networking complexity. Finch is the best library in Scala for microservice development. Gouldian is heavily inspired by Finch.

The library solves few practical problems of HTTP service development in Golang:

  • The library support opaque migration of HTTP service between traditional, containers and serverless environments. The api implementation remains source compatible regardless the execution environment; The library supports integration with
    • Golang standard HTTP server: http.Request
    • AWS API Gateway REST API (payload 1.0): APIGatewayProxyRequest
    • AWS API Gateway HTTP API and Lambda Function URL (payload 2.0): APIGatewayV2HTTPRequest
  • The library enforces a type safe, pattern-based approach for api definition: handlers receive a typed struct and never touch the raw request.
  • A request has three outcomes, not two: not my route (404/405/406/415), my route, bad input (400 RFC 9457 problem naming the invalid value) and success.
  • Fast, zero allocation routing

Installing

The library requires Go 1.27 or later. v3 is a major version, see MIGRATION-v3.md if you come from v2.

  1. Use go get to retrieve the library and add it as dependency to your application.
go get -u github.com/fogfish/gouldian/v3
  1. Import it in your code
import (
  µ "github.com/fogfish/gouldian/v3"
)

Quick Example

Here is minimal "Hello World!" example that matches any HTTP requests to /hello endpoint. You can run this example locally see the instructions.

package main

import (
  "net/http"

  µ "github.com/fogfish/gouldian/v3"
  ø "github.com/fogfish/gouldian/v3/output"
  "github.com/fogfish/gouldian/v3/server/httpd"
)

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!"),
      )
    },
  )
}

The same routes run in AWS Lambda:

api := µ.NewServer(µ.WithCORS(&µ.CORS{Origins: []string{"https://app.example"}})).Mount(hello())

lambda.Start(apigatewayv2.Handler(api)) // HTTP API, Function URL
lambda.Start(apigateway.Handler(api))   // REST API
http.ListenAndServe(":8080", httpd.Handler(api))

Benchmark

The library uses go-http-routing-benchmark methodology for benchmarking, using structure of GitHub API as primary benchmark. See bench for the v2 baseline, the v3 results and the comparison script (python3 bench/compare.py).

Next steps

  • Study User Guide.

  • Check build-in collection of endpoints to deal with HTTP request: path, query param, http header, body and other

  • Endpoint always returns some Output that defines HTTP response. There are three cases of output: HTTP Success, HTTP Failure and general error. See Output type.

  • See example folder for other advanced use-case.

  • Learn about microservice deployment with AWS CDK, in case of serverless development

How To Contribute

The library is Apache 2.0 licensed and accepts contributions via GitHub pull requests:

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

The build and testing process requires Go version 1.27 or later.

Build and run in your development console.

git clone https://github.com/fogfish/gouldian
cd gouldian
go test -race ./...
go test -run=^$ -bench=. -cpu 1

commit message

The commit message helps us to write a good release note, speed-up review process. The message should address two question what changed and why. The project follows the template defined by chapter Contributing to a Project of Git book.

bugs

If you experience any issues with the library, please let us know via GitHub issues. We appreciate detailed and accurate reports that help us to identity and replicate the issue.

License

See LICENSE

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

Examples

Constants

View Source
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

View Source
const (
	// Any constant matches any term
	Any = "_"
)
View Source
const DefaultBodyLimit int64 = 6 << 20

DefaultBodyLimit is the default limit of the request body (6 MiB, the payload limit of AWS Lambda).

View Source
const Version = "gouldian/v3.1.0"

Version of the library

Variables

View Source
var (
	ErrBodyRequired = errors.New("body is required")
	ErrBodyTooLarge = errors.New("body is too large")
	ErrMethod       = errors.New("method is not allowed")
)

Common failures

View Source
var ErrNoMatch error = NoMatchAny

ErrNoMatch is the generic NoMatch outcome

Functions

func DefaultIssue

func DefaultIssue(issue Issue, cause error) (string, []byte)

DefaultIssue renders RFC 9457 `application/problem+json`

func FromContext

func FromContext[S any](ctx *Context, val *S) error

FromContext decodes the context into structure

func Optics2

func Optics2[T, A, B any](attr ...string) (Lens, Lens)

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

func Optics3[T, A, B, C any](attr ...string) (Lens, Lens, Lens)

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

func Optics4[T, A, B, C, D any](attr ...string) (Lens, Lens, Lens, Lens)

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

func Optics5[T, A, B, C, D, E any](attr ...string) (Lens, Lens, Lens, Lens, Lens)

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

func Optics6[T, A, B, C, D, E, F any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens)

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

func Optics7[T, A, B, C, D, E, F, G any](attr ...string) (Lens, Lens, Lens, Lens, Lens, Lens, Lens)

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

func RegisterCodec[T any](decode func(string) (T, error))

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

func NewContext(ctx context.Context) *Context

NewContext create a new context for HTTP request

func (*Context) Free

func (ctx *Context) Free()

Free the context

func (*Context) Put

func (ctx *Context) Put(lens Lens, str string) error

Put injects value to the context. A value that cannot be decoded is a Failure.

func (*Context) Query

func (ctx *Context) Query() Query

Query returns the parsed query string

func (*Context) Route added in v3.1.0

func (ctx *Context) Route() *Route

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

func (ctx *Context) Set(key, val any)

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.

func (*Context) Value added in v3.1.0

func (ctx *Context) Value(key any) any

Value returns the attribute of the request (see Set), or the value of the context of the caller. It makes attributes visible to any function that takes the context as context.Context.

type Endpoint

type Endpoint func(*Context) error

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

func Authorization(f func(string, string) error) Endpoint

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

func Body(lens Lens) Endpoint

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 BodyMaybe

func BodyMaybe(lens Lens) Endpoint

BodyMaybe is like Body, but an empty body is not an error.

func FMap

func FMap[A any](f func(*Context, *A) error) Endpoint

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[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

func HeaderAny(hdr string) Endpoint

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

func HeaderMaybe(header string, lens Lens) Endpoint

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

func JWT[T Pattern](claim JWTClaim, val T) Endpoint

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

func JWTAllOf(claim JWTClaim, vals ...string) Endpoint

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

func JWTMaybe(claim JWTClaim, lens Lens) Endpoint

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

func JWTOneOf(claim JWTClaim, vals ...string) Endpoint

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 Join

func Join(seq ...Endpoint) Endpoint

Join builds product endpoint from sequence

func Lenient

func Lenient(e Endpoint) Endpoint

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

func Map[A, B any](f func(*Context, *A) (*B, error)) Endpoint

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

func Method(verb string) Endpoint

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 Or

func Or(seq ...Endpoint) Endpoint

Or builds co-product endpoint from sequence

func Param

func Param[T Pattern](key string, val T) Endpoint

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

func ParamAny(key string) Endpoint

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

func ParamJSON(key string, lens Lens) Endpoint

ParamJSON matches a param key to struct. It assumes that key holds JSON value as url encoded string

func ParamMaybe

func ParamMaybe(key string, lens Lens) Endpoint

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

func ParamMaybeJSON(key string, lens Lens) Endpoint

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

func Params(lens Lens) Endpoint

Params lifts all Query parameters to struct

type MyRequest struct {
	Params MyType `content:"form"`
}
var params = µ.Optics1[MyRequest, MyType]()
µ.GET(µ.Params(params))

func Trace

func Trace(name string, e Endpoint) Endpoint

Trace logs (debug level) the outcome of the endpoint, use it to understand why the request is not matched.

func (Endpoint) Or

func (a Endpoint) Or(b Endpoint) Endpoint

Or builds co-product Endpoint

func (Endpoint) Then

func (a Endpoint) Then(b Endpoint) Endpoint

Then builds product Endpoint

type Endpoints

type Endpoints []Endpoint

Endpoints is sequence of Endpoints

func (Endpoints) Join

func (seq Endpoints) Join(ctx *Context) (err error)

Join builds product endpoint from sequence

func (Endpoints) Or

func (seq Endpoints) Or(ctx *Context) error

Or builds co-product endpoint from sequence

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"}

func (*Failure) Detail

func (f *Failure) Detail() string

Detail is a human-readable explanation, it is safe to show to the client.

func (*Failure) Error

func (f *Failure) Error() string

func (*Failure) Pointer

func (f *Failure) Pointer() string

Pointer identifies the invalid value: RFC 6901 for the body, the name of param or header otherwise.

func (*Failure) Unwrap

func (f *Failure) Unwrap() error

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

type Guard func(ctx *Context) error

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

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

Matches value of HTTP header

func (HeaderEnumTransferEncoding) To

Matches value of HTTP header

type HeaderOf

type HeaderOf[T MatchableHeaderValues] string

Internal type

func (HeaderOf[T]) Any

func (h HeaderOf[T]) Any(ctx *Context) error

Any is a wildcard matcher of header. It fails if header is not defined.

func (HeaderOf[T]) Is

func (h HeaderOf[T]) Is(value T) Endpoint

Is matches a header to defined literal value.

func (HeaderOf[T]) To

func (h HeaderOf[T]) To(lens Lens) Endpoint

To matches header value to the request context. It uses lens abstraction to decode HTTP header into Golang type. The Endpoint is NoMatch if the header is absent, it is Failure if the value cannot be decoded to the target 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

func NewIssue

func NewIssue(status int) Issue

NewIssue creates instance of Issue

type IssueHandler added in v3.1.0

type IssueHandler func(ctx *Context, issue Issue, cause error, out *Output)

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

type IssueRenderer func(issue Issue, cause error) (contentType string, body []byte)

IssueRenderer converts the failure to the body of response

type JWTClaim

type JWTClaim func(Token) string

JWTClaim is function type to extract claims from token

type Lens

type Lens struct{ optics.Lens }

Lens is a setter of decoded HTTP value to a field of struct. The decoder is chosen once when the lens is constructed:

  1. field tag `content:"json"`, `content:"json,strict"`, `content:"form"`;
  2. decoder registered by RegisterCodec;
  3. encoding.TextUnmarshaler (the type validates itself);
  4. string, bool, int*, uint*, float*, time.Duration, []byte (raw), slices of them (repeated param or tag `sep:","`), pointers;
  5. struct is JSON by default.

Unsupported type panics when the lens is constructed (at start-up).

func At

func At[T any](field string) Lens

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

func Optics1

func Optics1[T, A any](attr ...string) Lens

Optics1 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 (hseq v1.3.2).

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.

func (NoMatch) Error

func (err NoMatch) Error() string

type Observer added in v3.1.0

type Observer func(ctx *Context, out *Output, elapsed time.Duration)

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

func WithBodyLimit(n int64) Option

WithBodyLimit sets the limit of request body (413 if exceeded). The default is 6 MiB, 0 disables the limit.

func WithCORS

func WithCORS(cors *CORS) Option

WithCORS enables CORS, default is off.

func WithGuard added in v3.1.0

func WithGuard(guards ...Guard) Option

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

func WithLogRoutes(on bool) Option

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

func WithLogger(log *slog.Logger) Option

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

func WithObserver(observers ...Observer) Option

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

func WithRecover(on bool) Option

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 NewOutput

func NewOutput(status int) *Output

NewOutput creates HTTP response with given HTTP Status code

func (*Output) AddHeader

func (out *Output) AddHeader(header, value string)

AddHeader appends the header, existing values are kept (e.g. Set-Cookie).

func (Output) Error

func (out Output) Error() string

Output uses "error" interface

func (*Output) Free

func (out *Output) Free()

Free releases output

func (*Output) GetHeader

func (out *Output) GetHeader(header string) string

GetHeader returns the first value of the header

func (*Output) SetHeader

func (out *Output) SetHeader(header, value string)

SetHeader sets the header, it replaces the existing value(s).

func (*Output) SetIssue

func (out *Output) SetIssue(failure error, title ...string)

SetIssue marks the output as failed. It attaches the cause, the server logs it and renders the response body as RFC 9457 Problem Details (see WithIssue to customise it). The cause of 4xx is shown to the client as detail, the cause of 5xx is never exposed.

func (*Output) Unwrap

func (out *Output) Unwrap() error

Unwrap exposes the cause, so errors.Is and errors.As work

type Pattern

type Pattern interface{ string | Lens }

Pattern is a union type of allowed params to matcher functions

type Query

type Query map[string][]string

Query of HTTP request

func (Query) Get

func (query Query) Get(key string) (string, bool)

Get returns the first value of the parameter

func (Query) GetAll

func (query Query) GetAll(key string) ([]string, bool)

GetAll returns all values of the (repeated) parameter

type ReadableHeaderValues

type ReadableHeaderValues interface {
	int | string | time.Time
}

type Result

type Result func(*Output) error

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

func ANY(path Routable, arrows ...Endpoint) Routable

ANY composes Endpoints into Routable that matches HTTP any request.

e := µ.ANY(
  µ.URI(µ.Path("foo"), µ.Path("bar")),
  ...
)

func DELETE

func DELETE(path Routable, arrows ...Endpoint) Routable

DELETE composes Endpoints into Routable that matches HTTP DELETE request.

e := µ.DELETE(
  µ.URI(µ.Path("foo"), µ.Path("bar")),
  ...
)

func GET

func GET(path Routable, arrows ...Endpoint) Routable

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

func HTTP(verb string, path Routable, arrows ...Endpoint) Routable

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

func Named(name string, route Routable) Routable

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

func PATCH(path Routable, arrows ...Endpoint) Routable

PATCH composes Endpoints into Routable that matches HTTP PATCH request.

e := µ.PATCH(
  µ.URI(µ.Path("foo"), µ.Path("bar")),
  ...
)

func POST

func POST(path Routable, arrows ...Endpoint) Routable

POST composes Endpoints into Routable that matches HTTP POST request.

e := µ.POST(
  µ.URI(µ.Path("foo"), µ.Path("bar")),
  ...
)

func PUT

func PUT(path Routable, arrows ...Endpoint) Routable

PUT composes Endpoints into Routable that matches HTTP PUT request.

e := µ.PUT(
  µ.URI(µ.Path("foo"), µ.Path("bar")),
  ...
)

func URI

func URI(segments ...Segment) Routable

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

func URIf(uri string, lenses ...Lens) Routable

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.

func (Route) String

func (r Route) String() string

String is "METHOD /path", ":" is a variable, "_" any segment and "*" the rest of the path.

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.

func NewRoutes

func NewRoutes(seq ...Routable) *Routes

NewRoutes creates new routing table

func (*Routes) Endpoint

func (r *Routes) Endpoint() Endpoint

Endpoint converts routing table to Endpoint

type Segment

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

Segment union type, make URI type safe

func Path

func Path[T Pattern](segment T) Segment

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

func PathAll

func PathAll(segment Lens) Segment

PathAll is an endpoint to match entire remaining path of URI

func PathAny

func PathAny() Segment

PathAny is a synonym of µ.Path("_"), it matches any segments

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

func NewServer(opts ...Option) *Server

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

func (s *Server) Dispatch(c *Context) *Output

Dispatch executes the request. It never returns nil, the output must be released with Output.Free once it is sent.

func (*Server) Mount

func (s *Server) Mount(routes ...Routable) *Server

Mount adds routes to the server

func (*Server) NewContext

func (s *Server) NewContext(ctx context.Context, r *http.Request) *Context

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.

func (*Server) Release

func (s *Server) Release(c *Context)

Release returns the context to the pool

type Source

type Source uint8

Source of the input that causes a failure

const (
	SourceUnknown Source = iota
	SourcePath
	SourceParam
	SourceHeader
	SourceBody
	SourceJWT
)

func (Source) String

func (s Source) String() string

type Token

type Token map[string]any

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

func NewToken(raw map[string]interface{}) Token

NewToken creates access token object from claims. It never panics, the claims keep their types. Null claims are ignored.

func (Token) Bool

func (t Token) Bool(claim string) (bool, bool)

Bool returns boolean claim

func (Token) ClientID

func (t Token) ClientID() string

ClientID associated with token

func (Token) Exp

func (t Token) Exp() string

Exp -ires after

func (Token) Get

func (t Token) Get(claim string) (any, bool)

Get claim as is

func (Token) Iss

func (t Token) Iss() string

Iss -uer of token

func (Token) Jti

func (t Token) Jti() string

Jti is unique JWT token identity

func (Token) Number

func (t Token) Number(claim string) (float64, bool)

Number returns numeric claim (e.g. exp, iat, nbf).

func (Token) Scope

func (t Token) Scope() string

Scope of the token

func (Token) String

func (t Token) String(claim string) 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.

func (Token) Strings

func (t Token) Strings(claim string) []string

Strings returns claim as list of strings, a string is split by space.

func (Token) Sub

func (t Token) Sub() string

Sub -ject of token

func (Token) Username

func (t Token) Username() string

Username associated with token

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
)

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

Jump to

Keyboard shortcuts

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