Documentation
¶
Index ¶
- func AddHandler(path string, handler http.HandlerFunc)
- func AddMiddleware(middleware MiddlewareFunc)
- func ClearServer()
- func ParseRequest(r *http.Request, req any) error
- func StartServer(ctx context.Context, addr string) error
- func ValidateStruct(i any) error
- func WriteError(w http.ResponseWriter, status int, message string)
- func WriteJSON(w http.ResponseWriter, status int, data any)
- type MiddlewareFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddHandler ¶ added in v1.1.0
func AddHandler(path string, handler http.HandlerFunc)
AddHandler registers a new HTTP handler for the specified path. Usage: AddHandler("GET /path", handlerFunction) Basically the same as http.HandleFunc but with a custom server instance.
func AddMiddleware ¶ added in v1.1.0
func AddMiddleware(middleware MiddlewareFunc)
MiddlewareFunc defines the type for middleware functions. The first middleware added is the most nested one.
func ClearServer ¶ added in v1.1.3
func ClearServer()
ClearServer resets the global server instance. This is useful for testing purposes to ensure a clean state.
func ParseRequest ¶ added in v1.1.0
ParseRequest parses the HTTP request and populates the provided struct with the data from the request. It supports parsing from context, headers, path parameters, query parameters, and JSON body.
Example usage:
type MyRequest struct {
ID int `ctx:"id"`
Name string `header:"X-Name"`
Age int `path:"age"`
Tags []string `query:"tags"`
Data MyData `body:"json"`
}
var req MyRequest
err := ParseRequest(r, &req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
func StartServer ¶ added in v1.1.0
StartServer initializes and starts the server with the given address. It will return once the server is stopped or an error occurs.
func ValidateStruct ¶ added in v1.1.0
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, message string)
WriteError writes an error message to the http.ResponseWriter with the specified status code. This is a utility function to handle errors in a consistent way across your handlers.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, data any)
WriteJSON writes a JSON response to the http.ResponseWriter. This should be the last step in your handler function, since it sets the Content-Type header to application/json, and can transform writer to send errors if the encoding fails.