treefarm

package
v0.0.0-...-da2a1ef Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package treefarm provides an example of how to handle OpenAPI callbacks. We create a server which plants trees. The client asks the server to plant a tree and requests a callback when the planting is done.

The server program will wait 1-5 seconds before notifying the client that a tree has been planted.

You can run the example by running these two commands in parallel go run ./server --port 8080 go run ./client --server http://localhost:8080

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOpenAPISpecJSON

func GetOpenAPISpecJSON() ([]byte, error)

GetOpenAPISpecJSON returns the raw OpenAPI spec as JSON bytes.

func Handler

func Handler(si ServerInterface) http.Handler

Handler creates http.Handler with routing matching OpenAPI spec.

func HandlerFromMux

func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler

HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux.

func HandlerFromMuxWithBaseURL

func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler

HandlerFromMuxWithBaseURL creates http.Handler with routing and a base URL.

func HandlerWithOptions

func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler

HandlerWithOptions creates http.Handler with additional options.

func NewTreePlantedCallbackRequest

func NewTreePlantedCallbackRequest(targetURL string, body TreePlantedJSONRequestBody) (*http.Request, error)

NewTreePlantedCallbackRequest creates a POST request for the callback with application/json body

func NewTreePlantedCallbackRequestWithBody

func NewTreePlantedCallbackRequestWithBody(targetURL string, contentType string, body io.Reader) (*http.Request, error)

NewTreePlantedCallbackRequestWithBody creates a POST request for the callback with any body

func TreePlantedCallbackHandler

func TreePlantedCallbackHandler(si CallbackReceiverInterface, errHandler func(w http.ResponseWriter, r *http.Request, err error), middlewares ...CallbackReceiverMiddlewareFunc) http.Handler

TreePlantedCallbackHandler returns an http.Handler for the TreePlanted callback. The caller is responsible for registering this handler at the appropriate path.

Types

type CallbackHttpError

type CallbackHttpError[E any] struct {
	StatusCode int
	Body       E
	RawBody    []byte
}

CallbackHttpError represents an HTTP error response from the callback. The type parameter E is the type of the parsed error body.

func (*CallbackHttpError[E]) Error

func (e *CallbackHttpError[E]) Error() string

type CallbackInitiator

type CallbackInitiator struct {
	// Doer for performing requests, typically a *http.Client with any
	// customized settings, such as certificate chains.
	Client HttpRequestDoer

	// A list of callbacks for modifying requests which are generated before sending over
	// the network.
	RequestEditors []RequestEditorFn
}

CallbackInitiator sends callback requests to target URLs. Unlike Client, it has no stored base URL — the full target URL is provided per-call.

func NewCallbackInitiator

func NewCallbackInitiator(opts ...CallbackInitiatorOption) (*CallbackInitiator, error)

NewCallbackInitiator creates a new CallbackInitiator with reasonable defaults.

func (*CallbackInitiator) TreePlanted

func (p *CallbackInitiator) TreePlanted(ctx context.Context, targetURL string, body TreePlantedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

TreePlanted sends a POST callback request with application/json body

func (*CallbackInitiator) TreePlantedWithBody

func (p *CallbackInitiator) TreePlantedWithBody(ctx context.Context, targetURL string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

TreePlantedWithBody sends a POST callback request Tree planting result notification

type CallbackInitiatorInterface

type CallbackInitiatorInterface interface {
	// TreePlantedWithBody sends a POST callback request
	TreePlantedWithBody(ctx context.Context, targetURL string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)
	TreePlanted(ctx context.Context, targetURL string, body TreePlantedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
}

CallbackInitiatorInterface is the interface specification for the callback initiator.

type CallbackInitiatorOption

type CallbackInitiatorOption func(*CallbackInitiator) error

CallbackInitiatorOption allows setting custom parameters during construction.

func WithCallbackHTTPClient

func WithCallbackHTTPClient(doer HttpRequestDoer) CallbackInitiatorOption

WithCallbackHTTPClient allows overriding the default Doer, which is automatically created using http.Client. This is useful for tests.

func WithCallbackRequestEditorFn

func WithCallbackRequestEditorFn(fn RequestEditorFn) CallbackInitiatorOption

WithCallbackRequestEditorFn allows setting up a callback function, which will be called right before sending the request. This can be used to mutate the request.

type CallbackReceiverInterface

type CallbackReceiverInterface interface {
	// Tree planting result notification
	// HandleTreePlantedCallback handles the POST callback request.
	HandleTreePlantedCallback(w http.ResponseWriter, r *http.Request)
}

CallbackReceiverInterface represents handlers for receiving callback requests.

type CallbackReceiverMiddlewareFunc

type CallbackReceiverMiddlewareFunc func(http.Handler) http.Handler

CallbackReceiverMiddlewareFunc is a middleware function for callback receiver handlers.

type Error

type Error struct {
	// Error code
	Code int32 `json:"code" form:"code"`
	// Error message
	Message string `json:"message" form:"message"`
}

#/components/schemas/Error

func (*Error) ApplyDefaults

func (s *Error) ApplyDefaults()

ApplyDefaults sets default values for fields that are nil.

type HttpRequestDoer

type HttpRequestDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HttpRequestDoer performs HTTP requests. The standard http.Client implements this interface.

type InvalidParamFormatError

type InvalidParamFormatError struct {
	ParamName string
	Err       error
}

InvalidParamFormatError is returned when a parameter has an invalid format.

func (*InvalidParamFormatError) Error

func (e *InvalidParamFormatError) Error() string

func (*InvalidParamFormatError) Unwrap

func (e *InvalidParamFormatError) Unwrap() error

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

MiddlewareFunc is a middleware function type.

type RequestEditorFn

type RequestEditorFn func(ctx context.Context, req *http.Request) error

RequestEditorFn is the function signature for the RequestEditor callback function. It may already be defined if client code is also generated; this is a compatible redeclaration.

type RequiredHeaderError

type RequiredHeaderError struct {
	ParamName string
	Err       error
}

RequiredHeaderError is returned when a required header is missing.

func (*RequiredHeaderError) Error

func (e *RequiredHeaderError) Error() string

func (*RequiredHeaderError) Unwrap

func (e *RequiredHeaderError) Unwrap() error

type RequiredParamError

type RequiredParamError struct {
	ParamName string
}

RequiredParamError is returned when a required parameter is missing.

func (*RequiredParamError) Error

func (e *RequiredParamError) Error() string

type ServeMux

type ServeMux interface {
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

ServeMux is an abstraction of http.ServeMux.

type ServerInterface

type ServerInterface interface {
	// Request a tree planting
	// (POST /api/plant_tree)
	PlantTree(w http.ResponseWriter, r *http.Request)
}

ServerInterface represents all server handlers.

type ServerInterfaceWrapper

type ServerInterfaceWrapper struct {
	Handler            ServerInterface
	HandlerMiddlewares []MiddlewareFunc
	ErrorHandlerFunc   func(w http.ResponseWriter, r *http.Request, err error)
}

ServerInterfaceWrapper converts HTTP requests to parameters.

func (*ServerInterfaceWrapper) PlantTree

func (siw *ServerInterfaceWrapper) PlantTree(w http.ResponseWriter, r *http.Request)

PlantTree operation middleware

type SimpleCallbackInitiator

type SimpleCallbackInitiator struct {
	*CallbackInitiator
}

SimpleCallbackInitiator wraps CallbackInitiator with typed responses for operations that have unambiguous response types. Methods return the success type directly, and HTTP errors are returned as *CallbackHttpError[E] where E is the error type.

func NewSimpleCallbackInitiator

func NewSimpleCallbackInitiator(opts ...CallbackInitiatorOption) (*SimpleCallbackInitiator, error)

NewSimpleCallbackInitiator creates a new SimpleCallbackInitiator which wraps a CallbackInitiator.

type StdHTTPServerOptions

type StdHTTPServerOptions struct {
	BaseURL          string
	BaseRouter       ServeMux
	Middlewares      []MiddlewareFunc
	ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}

StdHTTPServerOptions configures the StdHTTP server.

type TooManyValuesForParamError

type TooManyValuesForParamError struct {
	ParamName string
	Count     int
}

TooManyValuesForParamError is returned when a parameter has too many values.

func (*TooManyValuesForParamError) Error

type Tree

type Tree struct {
	// Where to plant the tree (e.g. "north meadow")
	Location string `json:"location" form:"location"`
	// What kind of tree to plant (e.g. "oak")
	Kind string `json:"kind" form:"kind"`
}

#/components/schemas/Tree A tree to be planted

func (*Tree) ApplyDefaults

func (s *Tree) ApplyDefaults()

ApplyDefaults sets default values for fields that are nil.

type TreePlantedJSONRequestBody

type TreePlantedJSONRequestBody = TreePlantingResult

type TreePlantingRequest

type TreePlantingRequest struct {
	// Where to plant the tree (e.g. "north meadow")
	Location string `json:"location" form:"location"`
	// What kind of tree to plant (e.g. "oak")
	Kind string `json:"kind" form:"kind"`
	// URL to receive the planting result callback
	CallbackURL string `json:"callbackUrl" form:"callbackUrl"`
}

#/components/schemas/TreePlantingRequest A tree planting request, combining the tree details with a callback URL for completion notification.

func (*TreePlantingRequest) ApplyDefaults

func (s *TreePlantingRequest) ApplyDefaults()

ApplyDefaults sets default values for fields that are nil.

type TreePlantingResult

type TreePlantingResult struct {
	// Where to plant the tree (e.g. "north meadow")
	Location string `json:"location" form:"location"`
	// What kind of tree to plant (e.g. "oak")
	Kind string `json:"kind" form:"kind"`
	// Unique identifier for this planting request
	ID UUID `json:"id" form:"id"`
	// Whether the tree was successfully planted
	Success bool `json:"success" form:"success"`
}

#/components/schemas/TreePlantingResult The result of a tree planting operation, sent via callback

func (*TreePlantingResult) ApplyDefaults

func (s *TreePlantingResult) ApplyDefaults()

ApplyDefaults sets default values for fields that are nil.

type TreeWithID

type TreeWithID struct {
	// Where to plant the tree (e.g. "north meadow")
	Location string `json:"location" form:"location"`
	// What kind of tree to plant (e.g. "oak")
	Kind string `json:"kind" form:"kind"`
	// Unique identifier for this planting request
	ID UUID `json:"id" form:"id"`
}

#/components/schemas/TreeWithId A tree with a server-assigned identifier

func (*TreeWithID) ApplyDefaults

func (s *TreeWithID) ApplyDefaults()

ApplyDefaults sets default values for fields that are nil.

type UUID

type UUID = uuid.UUID

type UnescapedCookieParamError

type UnescapedCookieParamError struct {
	ParamName string
	Err       error
}

UnescapedCookieParamError is returned when a cookie parameter cannot be unescaped.

func (*UnescapedCookieParamError) Error

func (e *UnescapedCookieParamError) Error() string

func (*UnescapedCookieParamError) Unwrap

func (e *UnescapedCookieParamError) Unwrap() error

type UnmarshalingParamError

type UnmarshalingParamError struct {
	ParamName string
	Err       error
}

UnmarshalingParamError is returned when a parameter cannot be unmarshaled.

func (*UnmarshalingParamError) Error

func (e *UnmarshalingParamError) Error() string

func (*UnmarshalingParamError) Unwrap

func (e *UnmarshalingParamError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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