Documentation
¶
Overview ¶
This package is designed for defining and managing HTTP APIs, with a focus on simplifying the API creation process and providing auto-generated API documentation. By using a declarative syntax, users can easily define API endpoints, request parameters, and response formats while automatically generating detailed API documentation.
Key Features ¶
- Declarative API Definition: Define API paths, methods, and handlers using a clean, declarative syntax.
- Automatic API Documentation: Automatically generates documentation based on the API definitions, reducing the need for manual documentation maintenance.
- Parameter Validation: Supports request parameter validation and documentation, ensuring API robustness.
- Error Handling: Built-in error handling mechanism provides friendly responses for invalid requests and errors.
Index ¶
- func AllowCookie(yesno bool)
- func ApiOnExit(r *http.Request, rep ReplySpec)
- func FixedReplyFields(args map[string]any)
- func IsCookieAllowed() bool
- func JSONMarshaller() *internal.JSONMarshallerOption
- func LoadLanguage(tag language.Tag, trans map[string]string)
- func Register(a API, mx ...*http.ServeMux)
- func WithGlobalActions(as ...Action)
- func WithLangSpecifier(lang string)
- func WithPanicLogger(f func(mesg string, trace []string))
- func WithPostResponseTrace(f func(*http.Request))
- func WithServiceInfo(spec ServiceInfo)
- func WithTraceFlagFunc(f func(*http.Request) bool)
- type API
- type Action
- type ApiSpec
- type NetRange
- type ParamSpec
- type ReplyDesc
- type ReplySpec
- type ServiceInfo
- type TraceContext
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApiOnExit ¶
ApiOnExit is called internally by the framework to end the trace context, and call the registered tracer. If no tracer is registered, nothing happens.
func FixedReplyFields ¶
Add fixed fields to JSON reply. For example:
FixedReplyFields(map[string]any{ "version": "1.0.0", "host": "alpha", })
This will add "version" and "host" fields to all JSON replies, which can be used for debugging. Note that if you specify reserved fields like "code", "data" and "mesg", they will not be actually used when producing API reply.
func JSONMarshaller ¶
func JSONMarshaller() *internal.JSONMarshallerOption
Returns JSON Marshaller option object, which is used to customize JSON reply keys in API style replies.
func LoadLanguage ¶
Exposes internal.LoadLanguage
func Register ¶
Registers an API instance. `mx` can be zero or more http.ServeMux instances. If none are provided, the API will be registered with http.DefaultServeMux. In this case, the application only needs to define an http.Server object and call its ListenAndServe method:
svr := http.Server{Addr: ":8080"} panic(svr.ListenAndServe())
func WithGlobalActions ¶
func WithGlobalActions(as ...Action)
Define one or more global actions, which are executed for all HTTP handlers. Global actions are executed before handler specific actions.
func WithPanicLogger ¶
Exposes internal.WithPanicLogger
func WithPostResponseTrace ¶
Call WithPostResponseTrace to register a function to be called after the HTTP response is sent to client. The function will be called only if there is a trace context created for the request.
func WithServiceInfo ¶
func WithServiceInfo(spec ServiceInfo)
ServiceInfo is the service information to be attached to the trace context, see ServiceInfo for more information.
func WithTraceFlagFunc ¶
WithTraceFlagFunc is used to register a function to determine the Flag of Traceparent header. The registered function is called by ApiOnEnter.
Types ¶
type API ¶
Defines the interface for an API endpoint. The Endpoint() method returns the endpoint path as a string. The Spec() method provides the API specification, formatted using the provided message.Printer.
It also embeds the http.Handler interface, allowing the API to handle HTTP requests.
type Action ¶
Action represents a function signature used for handling HTTP requests within the hap package. It defines a callback function that takes three parameters:
- *arg.Args: A pointer to the arguments parsed from the request. See the documentation for arg.Args for more details.
- http.ResponseWriter: An interface used to construct the HTTP response.
- *http.Request: A pointer to the HTTP request being handled.
The function returns `any`, which allows it to return various types of responses depending on the logic implemented. This type is typically used to define the logic for processing HTTP requests and generating responses based on the request parameters and other conditions.
A handler can define one or more Actions, which are executed sequentially. The output of the previous Action determines whether the next Action will be executed. Although the output of an Action is defined as `any`, it does not mean any type of value can be returned. The allowed return value types and their handling logic are as follows:
- nil: If an Action returns nil, it indicates that all business logic has been processed and information has been returned to the client. Subsequent Actions will not be executed, and the framework will not return any data to the client.
- hap.ReplySpec: The Action has completed the business logic and returned the final result. The framework will serialize and send the returned data to the client.
- error: If the returned type is error, it will be converted to HTTP/500 information and sent to the client.
- *arg.Args: Indicates that the Action has only processed input parameters or performed part of the business logic. In this case, the next Action will be executed, and the Args parameter passed in will be the result of the previous Action's processing.
func AllowRemoteFrom ¶
This Action checks whether the request comes from allowed IP ranges. `allowForward` determines if frontend proxying is allowed; if true, the check will consider the X-Forwarded-For HTTP header; if false, it will rely on the RemoteAddr of the request. `nr` is a NetRange object. See the example below:
_, lo4, _ = net.ParseCIDR("127.0.0.0/8") _, lo6, _ = net.ParseCIDR("::1/128") nr := hap.NewNetRange(lo4, lo6) hap.Register(api.New("/api/log").WithHandlers( handler.GET().WithActions( hap.AllowRemoteFrom(false, nr), getLogMessage, ).WithHelp("View log message") ))
type ApiSpec ¶
type ApiSpec struct { Tags url.Values `json:"tags,omitempty"` Endpoint string `json:"endpoint"` Method string `json:"method"` Help []string `json:"help,omitempty"` Params []ParamSpec `json:"params,omitempty"` Output []ReplyDesc `json:"output,omitempty"` }
API specification used for documentation.
type NetRange ¶
type NetRange struct {
// contains filtered or unexported fields
}
Represents a collection of network ranges stored in a slice of net.IPNet. This structure is used for access control in HTTP requests.
func NetRangeFunc ¶
Creates a new NetRange object with a dynamic fetcher function. The key difference between this function and NewNetRange is illustrated in the example below:
func init() { hap.Register(api.New("/api/endpoint").WithHandlers{ handler.GET().WithActions( hap.AllowRemoteFrom(true, hap.NetRangeFunc(cfg.SafeNets)), handleEndpoint, ) }) }
In this example, the HTTP handlers are defined in the init() function to ensure they are automatically executed. At the time when init() is called, the application's configuration has not yet been initialized. By using NetRangeFunc, the actual network ranges are fetched only when the handler is executed for the first time.
func (*NetRange) Get ¶
func (*NetRange) IsTrustedRequest ¶
Checks if an HTTP request `r` comes from an IP address within the NetRange. If `checkForward` is true, the function will check the X-Forwarded-For header (if present); otherwise, it will use r.RemoteAddr. Regardless of the NetRange contents, local loopback addresses (IPv4/IPv6) are always allowed.
In most cases, you should use AllowRemoteFrom, which internally uses this function.
type ParamSpec ¶
type ParamSpec struct { Default *string `json:"default,omitempty"` Name string `json:"name"` Type string `json:"type"` Rules [][]string `json:"rules,omitempty"` Help []string `json:"help,omitempty"` Required bool `json:"required"` }
Parameter specification used for documentation.
type ReplyDesc ¶
type ReplyDesc struct { Spec ReplySpec `json:"spec"` Mime string `json:"mime"` Raw bool `json:"raw"` }
Reply specification used for documentation.
type ReplySpec ¶
Exposes the private 'reply' struct.
func RawReply ¶
Create a raw reply with an HTTP status code. Unlike the HAP API style Reply, a raw reply allows setting its MIME type using WithMimeType. For example:
func getAvatar(a *arg.Args, w http.ResponseWriter, r *http.Request) any { uid := arg.Get[int64](a, "user_id") img := getAvatar(uid) return hap.RawReply(http.StatusOK).WithData(img).WithMimeType("image/jpeg") }
func Reply ¶
Create a HAP API style reply. The reply will be sent to the client in JSON format, with the following structure:
{ "code": 200, // status code must be an integer "data": "data", // data can be any type allowed by JSON "mesg": "help message" // help message }
Among these properties, only `code` is required, while `data` and `mesg` are optional. Typically, `data` is included in successful responses, and `mesg` is used to explain the failure reason in case of an error. The success or failure of the response is indicated by the `code`. A common convention is to use HTTP status codes for `code`, as described in the HAP specification. Example:
func setAvatar(a *arg.Args, w http.ResponseWriter, r *http.Request) any { uid := arg.Get[int64](a, "user_id") err := setAvatar(uid, r.Body) if err != nil { return hap.Reply(http.StatusInternalServerError).WithHelp(err.Error()) } return hap.Reply(http.StatusOK) }
type ServiceInfo ¶
type ServiceInfo struct { Name string // service.name Address string // service.instance.id Version string // service.version Environ string // deployment.environment.name }
ServiceInfo describes the HTTP service, providing information like service name, server IP address, service version, and deployment environment (alpha/beta/stable).
type TraceContext ¶
type TraceContext struct { Service *ServiceInfo Props map[string]string Indexes map[string]string TraceId string SpanId string Route string //handler matching pattern Args *arg.Args Reply ReplySpec ParentSpanId string StartTime int64 EndTime int64 Flags byte }
W3C TraceContext: https://www.w3.org/TR/trace-context/
func ApiOnEnter ¶
func ApiOnEnter(r *http.Request, entry string) *TraceContext
ApiOnEnter is called internally by the framework to create a trace context
func GetTraceContext ¶
func GetTraceContext(r *http.Request) *TraceContext
GetTraceContext returns the trace context from the request context
func (*TraceContext) Index ¶
func (tc *TraceContext) Index(key, val string)
Index adds indexed key-value pair to the trace context.
func (*TraceContext) Prop ¶
func (tc *TraceContext) Prop(key, val string)
Prop adds non-indexed key-value pair to the trace context.
func (TraceContext) Traceparent ¶
func (tc TraceContext) Traceparent() string
Traceparent returns the W3C Traceparent header value for the trace context.