The apictx package provides a set of utilities to streamline handling HTTP requests and responses in a Go web application. It includes features for request context management, error handling, validation, and more.
To use the apictx package, you need to install it first. Add it to your project using go get:
go get github.com/sivsivsree/apictxThe Context struct is used to manage request and response objects, as well as the current user. Create a new context by using the NewContext function:
func NewContext(w http.ResponseWriter, r *http.Request, user User) Context {
return Context{
CurrentUser: user,
writer: w,
request: r,
}
}The Context struct provides methods to bind request data to Go structs. The Bind method binds and validates the request data:
func (c *Context) Bind(data interface{}) *HttpErrorTo bind without validation, use the BindWithoutValidation method:
func (c *Context) BindWithoutValidation(data interface{}) errorThe Context struct provides a method to send JSON responses:
func (c *Context) JSON(code int, data interface{})The package includes an HttpError struct for handling HTTP errors:
type HttpError struct {
err error
msg string
statusCode int
}
func NewHttpError(msg string, err error, statsuCode ...int) *HttpErrorUse the HandleError function to handle errors in your handlers:
func HandleError(w http.ResponseWriter, r *http.Request, err error, overRideStatusCode ...int)The Handler function wraps your context function, making it compatible with http.HandlerFunc:
func Handler(c ContextFunc) http.HandlerFuncHere are a few examples to help you get started:
package main
import (
"net/http"
"github.com/sivsivsree/apictx"
)
func main() {
http.HandleFunc("/example", apictx.Handler(ExampleHandler))
http.ListenAndServe(":8080", nil)
}
func ExampleHandler(ctx *apictx.Context) error {
var data struct {
Name string `query:"name" validate:"required"`
Age int `query:"age" validate:"gte=0"`
}
if err := ctx.Bind(&data); err != nil {
return err
}
ctx.JSON(http.StatusOK, data)
return nil
}func ExampleHandler(ctx *apictx.Context) error {
return apictx.NewHttpError("an error occurred", errors.New("example error"), http.StatusInternalServerError)
}Contributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License. See the LICENSE file for details.