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 IsCookieAllowed() bool
- func JSONMarshaller() *internal.JSONMarshallerOption
- func LoadLanguage(tag language.Tag, trans map[string]string)
- func RawReply(code int) *reply
- func Register(a API, mx ...*http.ServeMux)
- func Reply(code int) *reply
- func SetGlobalCORS(enable bool, origin ...string)
- func WithGlobalActions(as ...Action)
- func WithLangSpecifier(lang string)
- func WithPanicLogger(f func(mesg string, trace []string))
- type API
- type Action
- type ApiSpec
- type NetRange
- type ParamSpec
- type ReplyDesc
- type ReplySpec
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 RawReply ¶
func RawReply(code int) *reply
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 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 Reply ¶
func Reply(code int) *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) }
func SetGlobalCORS ¶
Exposes internal.SetGlobalCORS
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
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 { Endpoint string `json:"endpoint"` Method string `json:"method"` Help []string `json:"help,omitempty"` Params []ParamSpec `json:"params,omitempty"` Output []ReplyDesc `json:"output,omitempty"` Tags url.Values `json:"tags,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 { Name string `json:"name"` Type string `json:"type"` Required bool `json:"required"` Default *string `json:"default,omitempty"` Rules [][]string `json:"rules,omitempty"` Help []string `json:"help,omitempty"` }
Parameter specification used for documentation.