hap

package module
v2.0.0-alpha.95 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 License: MIT Imports: 15 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllowCookie

func AllowCookie(yesno bool)

Exposes internal.AllowCookie

func IsCookieAllowed

func IsCookieAllowed() bool

Exposes internal.IsCookieAllowed

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

func LoadLanguage(tag language.Tag, trans map[string]string)

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

func Register(a API, mx ...*http.ServeMux)

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

func SetGlobalCORS(enable bool, origin ...string)

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 WithLangSpecifier

func WithLangSpecifier(lang string)

Exposes internal.WithLangSpecifier

func WithPanicLogger

func WithPanicLogger(f func(mesg string, trace []string))

Exposes internal.WithPanicLogger

Types

type API

type API interface {
	Endpoint() string
	Spec(*message.Printer) []ApiSpec
	http.Handler
}

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

type Action func(*arg.Args, http.ResponseWriter, *http.Request) any

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

func AllowRemoteFrom(allowForward bool, nr *NetRange) Action

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

func GlobalActions

func GlobalActions() []Action

Called by the framework to get all global actions.

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.

func Specs

func Specs(endPoint, method string, f *message.Printer) (as []ApiSpec)

Called by [api.ListAPIs] to generate API 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

func NetRangeFunc(f func() []net.IPNet) *NetRange

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 NewNetRange

func NewNetRange(ipn ...net.IPNet) *NetRange

Create a new NetRange object.

func (*NetRange) Add

func (nr *NetRange) Add(ipn ...net.IPNet)

Appends the provided `ipn` values to the NetRange's slice of net.IPNet.

func (*NetRange) Contains

func (nr *NetRange) Contains(ip net.IP) bool

Checks if an IP address is within the NetRange.

func (*NetRange) Get

func (nr *NetRange) Get() []net.IPNet

Returns the slice of net.IPNet stored within the NetRange.

func (*NetRange) IsTrustedRequest

func (nr *NetRange) IsTrustedRequest(r *http.Request, checkForward bool) bool

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.

func (*NetRange) Set

func (nr *NetRange) Set(ipn ...net.IPNet)

Replaces the NetRange's slice of net.IPNet with the provided `ipn` values.

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.

type ReplyDesc

type ReplyDesc struct {
	Mime string    `json:"mime"`
	Raw  bool      `json:"raw"`
	Spec ReplySpec `json:"spec"`
}

Reply specification used for documentation.

type ReplySpec

type ReplySpec = *reply

Exposes the private 'reply' struct.

Directories

Path Synopsis
Provides utilities for managing and processing arguments in a structured way.
Provides utilities for managing and processing arguments in a structured way.
Defines HTTP handlers.
Defines HTTP handlers.

Jump to

Keyboard shortcuts

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