Documentation
¶
Overview ¶
Package web is a collection of functions and types for building web services.
Index ¶
- Variables
- func ListenAndServe(ctx context.Context, c *ListenAndServeConfig) error
- func RespondError(logf logger.Logf, w http.ResponseWriter, err error)
- func RespondJSON(w http.ResponseWriter, response any)
- func RespondJSONError(logf logger.Logf, w http.ResponseWriter, err error)
- type CheckResponse
- type DebugHandler
- func (d *DebugHandler) Handle(slug, desc string, handler http.Handler)
- func (d *DebugHandler) HandleFunc(slug, desc string, handler http.HandlerFunc)
- func (d *DebugHandler) KV(k string, v any)
- func (d *DebugHandler) KVFunc(k string, v func() any)
- func (d *DebugHandler) Link(url, desc string)
- func (d *DebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type HealthFunc
- type HealthHandler
- type HealthResponse
- type ListenAndServeConfig
- type StatusErr
Constants ¶
This section is empty.
Variables ¶
var StaticFS = hashfs.NewFS(staticFS)
StaticFS is an embed.FS that contains static resources served on /static/ path prefix of ListenAndServe servers.
Functions ¶
func ListenAndServe ¶
func ListenAndServe(ctx context.Context, c *ListenAndServeConfig) error
ListenAndServe starts the HTTP server based on the provided ListenAndServeConfig.
func RespondError ¶
func RespondError(logf logger.Logf, w http.ResponseWriter, err error)
RespondError writes an error response in HTML format to w and logs the error using provided logger.Logf if error is ErrInternalServerError.
If the error is a StatusErr or wraps it, it extracts the HTTP status code and sets the response status code accordingly. Otherwise, it sets the response status code to http.StatusInternalServerError.
You can wrap any error with fmt.Errorf to create a StatusErr and set a specific HTTP status code:
// This will set the status code to 404 (Not Found). web.RespondError(w, fmt.Errorf("resource %w", web.ErrNotFound))
func RespondJSON ¶
func RespondJSON(w http.ResponseWriter, response any)
RespondJSON marshals the provided response object as JSON and writes it to the http.ResponseWriter. It sets the Content-Type header to application/json before marshalling. In case of marshalling errors, it writes an internal server error with the error message.
func RespondJSONError ¶
func RespondJSONError(logf logger.Logf, w http.ResponseWriter, err error)
RespondJSONError writes an error response in JSON format to w and logs the error using provided logger.Logf.
If the error is a StatusErr or wraps it, it extracts the HTTP status code and sets the response status code accordingly. Otherwise, it sets the response status code to http.StatusInternalServerError.
You can wrap any error with fmt.Errorf to create a StatusErr and set a specific HTTP status code:
// This will set the status code to 404 (Not Found). web.RespondJSONError(w, fmt.Errorf("resource %w", web.ErrNotFound)
Types ¶
type CheckResponse ¶
CheckResponse represents a status of an individual check.
type DebugHandler ¶
type DebugHandler struct {
// contains filtered or unexported fields
}
DebugHandler is an http.Handler that serves a debugging "homepage", and provides helpers to register more debug endpoints and reports.
The rendered page consists of two sections: informational key/value pairs and links to other pages.
Callers can add to these sections using the KV and Link helpers respectively.
Additionally, the Handle method offers a shorthand for correctly registering debug handlers and cross-linking them from /debug/.
Methods of DebugHandler can be safely called by multiple goroutines.
func Debugger ¶
func Debugger(logf logger.Logf, mux *http.ServeMux) *DebugHandler
Debugger returns the DebugHandler registered on mux at /debug/, creating it if necessary.
func (*DebugHandler) Handle ¶
func (d *DebugHandler) Handle(slug, desc string, handler http.Handler)
Handle registers handler at /debug/<slug> and creates a descriptive entry in /debug/ for it.
func (*DebugHandler) HandleFunc ¶
func (d *DebugHandler) HandleFunc(slug, desc string, handler http.HandlerFunc)
HandleFunc is like Handle, but accepts http.HandlerFunc instead of http.Handler.
func (*DebugHandler) KV ¶
func (d *DebugHandler) KV(k string, v any)
KV adds a key/value list item to /debug/.
func (*DebugHandler) KVFunc ¶
func (d *DebugHandler) KVFunc(k string, v func() any)
KVFunc adds a key/value list item to /debug/. v is called on every render of /debug/.
func (*DebugHandler) Link ¶
func (d *DebugHandler) Link(url, desc string)
Link adds a URL and description list item to /debug/.
func (*DebugHandler) ServeHTTP ¶
func (d *DebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
type HealthFunc ¶
HealthFunc is the health check function that reports the state of a particular subsystem.
type HealthHandler ¶
type HealthHandler struct {
// contains filtered or unexported fields
}
HealthHandler is an HTTP handler that returns information about the health status of the running service.
func Health ¶
func Health(mux *http.ServeMux) *HealthHandler
Health returns the HealthHandler registered on mux at /health, creating it if necessary.
func (*HealthHandler) RegisterFunc ¶
func (h *HealthHandler) RegisterFunc(name string, f HealthFunc)
RegisterFunc registers the health check function by the given name. If the health check function with this name already exists, RegisterFunc panics.
Health check function must be safe for concurrent use.
func (*HealthHandler) ServeHTTP ¶
func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
type HealthResponse ¶
type HealthResponse struct { OK bool `json:"ok"` Checks map[string]CheckResponse `json:"checks"` }
HealthResponse represents a response of the /health endpoint.
type ListenAndServeConfig ¶
type ListenAndServeConfig struct { // Addr is a network address to listen on (in the form of "host:port"). // // If Addr is not localhost and doesn't contain a port (in example, // "example.com" or "exp.astrophena.name"), the server accepts HTTPS // connections on :443, redirects HTTP connections to HTTPS on :80 and // automatically obtains a certificate from Let's Encrypt. Addr string // Mux is a http.ServeMux to serve. Mux *http.ServeMux // Logf specifies a logger to use. If nil, log.Printf is used. Logf logger.Logf // Debuggable specifies whether to register debug handlers at /debug/. Debuggable bool // DebugAuth specifies an optional function that's invoked on every request to // debug handlers at /debug/ to allow or deny access to them. If not provided, // all access is allowed. DebugAuth func(r *http.Request) bool // Ready specifies an optional function to be called when the server is ready // to serve requests. Ready func() }
ListenAndServeConfig is used to configure the HTTP server started by ListenAndServe.
All fields of ListenAndServeConfig can't be modified after ListenAndServe is called.
type StatusErr ¶
type StatusErr int
StatusErr is a sentinel error type used to represent HTTP status code errors.
const ( // ErrBadRequest represents a bad request error (HTTP 400). ErrBadRequest StatusErr = http.StatusBadRequest ErrUnauthorized StatusErr = http.StatusUnauthorized // ErrForbidden represents a forbidden access error (HTTP 403). ErrForbidden StatusErr = http.StatusForbidden // ErrNotFound represents a not found error (HTTP 404). ErrNotFound StatusErr = http.StatusNotFound // ErrMethodNotAllowed represents a method not allowed error (HTTP 405). ErrMethodNotAllowed StatusErr = http.StatusMethodNotAllowed // ErrInternalServerError represents an internal server error (HTTP 500). ErrInternalServerError StatusErr = http.StatusInternalServerError )