httpwrap
httpwrap is a Go library that provides convenient wrappers for popular HTTP routers (net/http, chi, fiber). It simplifies error handling in HTTP handlers by allowing them to return an error type. The wrappers automatically handle these errors, converting them into appropriate HTTP error responses.
Features
- Simplified error handling in HTTP handlers.
- Automatic conversion of
httperror.HttpError to corresponding HTTP status codes and messages.
- Support for RFC7807 Problem Details for HTTP APIs.
- Fallback to HTTP 500 Internal Server Error for other error types.
- Wrappers for:
- Standard
net/http (httpwrap)
go-chi/chi/v5 (chiwrap)
gofiber/fiber/v2 (fiberwrap)
- Customizable error callback for logging or other purposes (for
httpwrap and chiwrap).
Installation
To install httpwrap and its subpackages, use go get:
go get -u github.com/gosuda/httpwrap
httperror
The httperror package provides a convenient way to create Go errors that also carry specific HTTP status codes. This allows the httpwrap family of wrappers (httpwrap, chiwrap, fiberwrap) to automatically translate these errors into appropriate HTTP responses.
The package offers several functions to create these specialized errors:
httperror.New(statusCode int, message string) *HttpError: A generic function to create an error with any given HTTP statusCode and a custom message.
- Specific helper functions for common HTTP status codes, such as:
httperror.BadRequest(message string) *HttpError (for 400 Bad Request)
httperror.Unauthorized(message string) *HttpError (for 401 Unauthorized)
httperror.Forbidden(message string) *HttpError (for 403 Forbidden)
httperror.NotFound(message string) *HttpError (for 404 Not Found)
httperror.InternalServerError(message string) *HttpError (for 500 Internal Server Error)
- And many more, corresponding to standard HTTP status codes (e.g.,
MethodNotAllowed, Conflict, ServiceUnavailable, etc.).
When a handler in your application returns an error created by these functions (e.g., httperror.New() or httperror.BadRequest()), the respective wrapper will use the statusCode and message from this error to formulate the HTTP response. If a handler returns any other standard Go error, the wrappers will default to sending a 500 Internal Server Error.
Problem Details for HTTP APIs
The httperror package implements both RFC7807 and RFC9457 specifications for Problem Details for HTTP APIs, providing standardized ways to describe problems that occurred during HTTP requests.
RFC7807 Problem Details (Legacy)
RFC7807 was the original specification for Problem Details for HTTP APIs. It provides a standardized format for describing HTTP API errors.
RFC7807Error Struct
The RFC7807Error struct implements the error interface and follows the RFC7807 standard with the following fields:
Type: A URI reference that identifies the problem type. Defaults to "about:blank" if not specified.
Title: A short, human-readable summary of the problem type.
Status: The HTTP status code generated by the origin server.
Detail: A human-readable explanation specific to this occurrence of the problem.
Instance: A URI reference that identifies the specific occurrence of the problem.
Extensions: Additional members that provide information about the problem.
Creating RFC7807 Errors
You can create RFC7807 errors using helper functions with the 7807 suffix:
// Create a basic 400 Bad Request problem
err := httperror.BadRequestProblem7807("Invalid request parameters")
// Create a 404 Not Found problem with custom title
err := httperror.NotFoundProblem7807("User with ID 123 not found", "User Not Found")
// Add more context with fluent API
err := httperror.ForbiddenProblem7807("Insufficient permissions to access resource")
.WithType("https://example.com/errors/insufficient-permissions")
.WithInstance("/api/resources/123")
.WithExtension("resource_id", "123")
.WithExtension("required_role", "admin")
RFC9457 Problem Details (Recommended)
RFC9457 obsoletes RFC7807 and provides an improved specification for Problem Details for HTTP APIs with enhanced features and better guidance.
Key Improvements in RFC9457
- Registry for Common Problem Types: Standardized problem type URIs for common scenarios
- Multiple Problems Handling: Ability to describe multiple related problems in a single response
- Enhanced URI Guidance: Better guidance for dereferenceable vs non-dereferenceable type URIs
- Improved Security Considerations: Updated security guidelines and best practices
- Trace ID Support: Built-in support for debugging and tracking identifiers
RFC9457Error Struct
The RFC9457Error struct extends the RFC7807 concept with additional capabilities:
- All RFC7807 fields (Type, Title, Status, Detail, Instance, Extensions)
- Enhanced extension support for trace IDs, retry information, and multiple problems
- Validation methods to ensure RFC9457 compliance
- Common problem type registry for standardized error types
Creating RFC9457 Errors (Recommended)
You can create RFC9457 errors using helper functions with the 9457 suffix:
// Create a basic 400 Bad Request problem
err := httperror.BadRequestProblem9457("Invalid request parameters")
// Create a 404 Not Found problem with custom title
err := httperror.NotFoundProblem9457("User with ID 123 not found", "User Not Found")
// Add more context with fluent API
err := httperror.ForbiddenProblem9457("Insufficient permissions to access resource")
.WithType("https://example.com/errors/insufficient-permissions")
.WithInstance("/api/resources/123")
.WithExtension("resource_id", "123")
.WithExtension("required_role", "admin")
RFC9457 Enhanced Features
// Use common problem types from registry
err := httperror.BadRequestProblem9457("Validation failed")
// Automatically uses CommonProblemTypes.ValidationError
// Add trace ID for debugging
err := httperror.InternalServerErrorProblem9457("Database connection failed")
.WithTraceID("trace-abc123def456")
// Handle multiple related problems
validationProblems := []interface{}{
map[string]interface{}{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Email format is invalid",
},
map[string]interface{}{
"field": "age",
"code": "OUT_OF_RANGE",
"message": "Age must be between 0-120",
},
}
err := httperror.UnprocessableEntityProblem9457("Multiple validation errors")
.WithMultipleProblems(validationProblems)
// Rate limiting with retry information
err := httperror.TooManyRequestsProblem9457("Rate limit exceeded")
.WithRetryAfter(60)
.WithExtension("limit", 100)
.WithExtension("window", "1 minute")
Converting to HTTP Response
Both RFC7807Error and RFC9457Error types include a ToHttpError() method which converts the problem detail to a JSON representation for HTTP responses:
// In your HTTP handler
func myHandler(w http.ResponseWriter, r *http.Request) error {
// Some logic that might produce an error
if !userHasAccess {
// Using RFC9457 (recommended)
err := httperror.ForbiddenProblem9457("User does not have access to the resource")
.WithType("https://example.com/errors/access-denied")
.WithInstance(r.URL.Path)
.WithExtension("user_id", userId)
// Convert to HttpError for automatic handling by the wrapper
return err.ToHttpError()
}
// Rest of your handler code
return nil
}
When used with the httpwrap family of wrappers, this will automatically generate a JSON response like:
{
"type": "https://example.com/errors/access-denied",
"title": "Forbidden",
"status": 403,
"detail": "User does not have access to the resource",
"instance": "/api/resources/123",
"user_id": "user123"
}
Usage
Below are examples of how to use each wrapper.
1. httpwrap (for standard net/http)
This wrapper is for the standard library's http.ServeMux.
package main
import (
"fmt"
"net/http"
"github.com/gosuda/httpwrap/httperror"
"github.com/gosuda/httpwrap/wrapper/httpwrap"
)
func myHandler(w http.ResponseWriter, r *http.Request) error {
// Simulate some logic
shouldFail := r.URL.Query().Get("fail")
if shouldFail == "true" {
return httperror.BadRequest("Invalid request due to 'fail' parameter")
}
if shouldFail == "panic" {
return fmt.Errorf("something unexpected happened")
}
_, err := w.Write([]byte("Hello from httpwrap!"))
return err
}
func main() {
mux := httpwrap.NewMux(func(err error) {
// Optional: Custom error logging or handling
fmt.Printf("An error occurred: %v\n", err)
})
mux.Handle("/hello", myHandler)
fmt.Println("Server starting on :8080...")
if err := http.ListenAndServe(":8080", mux); err != nil {
fmt.Printf("Server failed to start: %v\n", err)
}
}
2. chiwrap (for go-chi/chi)
This wrapper is for go-chi/chi/v5.
package main
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/gosuda/httpwrap/httperror"
"github.com/gosuda/httpwrap/wrapper/chiwrap"
)
func myChiHandler(w http.ResponseWriter, r *http.Request) error {
param := chi.URLParam(r, "name")
if param == "" {
return httperror.BadRequest("Name parameter is missing")
}
if param == "error" {
return fmt.Errorf("internal server error triggered")
}
_, err := w.Write([]byte(fmt.Sprintf("Hello, %s, from chiwrap!", param)))
return err
}
func main() {
router := chiwrap.NewRouter(func(err error) {
// Optional: Custom error logging
fmt.Printf("Chiwrap encountered an error: %v\n", err)
})
router.Get("/greet/{name}", myChiHandler)
// You can also use other methods like Post, Put, Delete, etc.
// router.Post("/submit", func(w http.ResponseWriter, r *http.Request) error { ... })
// Mount the chiwrap router
chiRouter := chi.NewRouter() // Or your existing chi router
chiRouter.Mount("/chi", router) // Mount chiwrap.Router which implements http.Handler
fmt.Println("Chi server starting on :8081...")
if err := http.ListenAndServe(":8081", chiRouter); err != nil {
fmt.Printf("Chi server failed to start: %v\n", err)
}
}
3. fiberwrap (for gofiber/fiber)
This wrapper is for gofiber/fiber/v2.
package main
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gosuda/httpwrap/httperror"
"github.com/gosuda/httpwrap/wrapper/fiberwrap"
)
func myFiberHandler(c *fiber.Ctx) error {
userID := c.Params("id")
if userID == "0" {
return httperror.NotFound("User with ID 0 not found")
}
if userID == "panic" {
return fmt.Errorf("a critical error occurred")
}
return c.SendString(fmt.Sprintf("Hello from Fiber user %s!", userID))
}
func main() {
// Using a new Fiber app
fw := fiberwrap.NewWrapper()
app := fw.App()
// Or using an existing Fiber app
// existingApp := fiber.New()
// fw := fiberwrap.WithApp(existingApp)
// app := fw.App()
fw.Get("/fiber/user/:id", myFiberHandler)
// fw.Post("/fiber/data", func(c *fiber.Ctx) error { ... })
fmt.Println("Fiber server starting on :8082...")
if err := app.Listen(":8082"); err != nil {
fmt.Printf("Fiber server failed to start: %v\n", err)
}
}
Contributing
Contributions are welcome! Please feel free to submit a pull request or open an issue.
License
This project is licensed under the MIT License - see the LICENSE file for details.