AutoHTTP is a Go library designed to simplify the creation of HTTP APIs with the Echo framework. It leverages reflection to automatically handle request binding, validation, and response serialization based on your Go function signatures, significantly reducing boilerplate code.
- Automatic Routing: Define API endpoints simply by creating Go functions. AutoHTTP can infer HTTP methods (GET, POST, PUT, DELETE) and URL paths from function names (e.g.,
GetUser
,PostProduct
). - Automatic Request Binding & Validation: Request bodies (JSON), form data, query parameters, and path parameters are automatically bound to the input struct of your handler function. Built-in validation using
go-playground/validator
. - Automatic Response Handling: Return values from your handler functions are automatically serialized to JSON. Errors are handled gracefully, returning appropriate HTTP status codes.
- Middleware Support: Easily integrate any standard Echo middleware.
- Extensible Documentation Generation: Pluggable interface (
DocGenerator
) allows integration with various documentation generation tools.
go get github.com/Lexographics/autohttp
package main
import (
"github.com/Lexographics/autohttp"
)
// Define your request/response structures
type CreateUserInput struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
}
type GetUserInput struct {
ID int `query:"id" param:"id" validate:"required"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type NotFoundError struct {
Model string `json:"-"`
}
func (e *NotFoundError) Error() string {
return e.Model + " not found"
}
// StatusCode returns the HTTP status code that will be used in the response
func (e *NotFoundError) StatusCode() int {
return 404
}
// Define your API handlers
type UserAPI struct {
// Dependencies can be added here
}
func (api *UserAPI) PostUser(input CreateUserInput) (User, error) {
// Input is automatically bound and validated
// ... implementation to create user ...
newUser := User{
ID: 1,
Name: input.Name,
Email: input.Email,
}
// Return the created user (will be JSON serialized) and nil error
return newUser, nil
}
func (api *UserAPI) GetUser(input GetUserInput) (User, error) {
// You would typically fetch the user by id here
// Example:
if input.ID == 1 {
return User{ID: 1, Name: "Example User", Email: "user@example.com"}, nil
}
return User{}, &NotFoundError{Model: "User"}
}
func main() {
a := autohttp.New()
userAPI := &UserAPI{}
// Automatically register all methods in UserAPI struct starting with Get, Post, Put, Delete
// POST /user will be created from PostUser
// GET /user will be created from GetUser
// Note: Path parameter handling might require manual routing or specific conventions.
// The example shows basic auto-routing based on method name prefixes.
// For explicit path parameters like /user/:id, use Add or specific method helpers.
a.Auto(userAPI)
// Example of explicit routing
// a.Post("/users", userAPI.PostUser)
// a.Get("/users/:id", userAPI.GetUser) // Requires manual handling of path param 'id' in GetUser or framework support
// Start the server
a.GetEcho().Logger.Fatal(a.Start(":8080"))
}
AutoHTTP features a flexible documentation generation system. You can add any component that implements the DocGenerator
interface.
type DocGenerator interface {
Register(spec map[string]any) error
}
type RouteSpec struct {
Method string
Path string
InputType reflect.Type // The type of the input struct for the handler
}
One of the official DocGenerator
implementations provided is the postmangen
library, available at https://github.com/Lexographics/go-postmangen. It automatically creates a Postman collection based on your registered API routes.
postmangen
is a separate, optional library. You can use it alongside autohttp
if you need Postman documentation.
Installation:
go get github.com/Lexographics/go-postmangen
Usage:
package main
import (
"github.com/Lexographics/autohttp"
"github.com/Lexographics/go-postmangen" // Import postmangen
// ... other imports
)
// ... (API structs and handlers as before)
func main() {
// Initialize Postman generator
postman := postmangen.NewPostmanGen("My API", "Description of my API")
postman.AddVariable("base_url", "http://localhost:8080") // Add necessary environment variables
// Initialize AutoHTTP and add the Postman generator
a := autohttp.New().AddDocGenerator(postman)
userAPI := &UserAPI{}
a.Auto(userAPI) // Routes registered here will also be added to Postman
// ... Start server etc.
// Write the Postman collection to a file
err := postman.WriteToFile("my_api_postman.json")
if err != nil {
panic(err)
}
}
This will generate a my_api_postman.json
file that you can import into Postman.
Support for generating OpenAPI (Swagger) specifications is planned as another official DocGenerator
implementation.
The DocGenerator
interface is designed to be simple. Anyone can write their own documentation generator library to work with autohttp
. If you need documentation in a specific format (e.g., API Blueprint, AsciiDoc), you can create a package that implements DocGenerator
and integrates with autohttp
using the AddDocGenerator
method.
Contributions are welcome! Please feel free to submit issues and pull requests.
This project is licensed under the MIT License - see the LICENSE file for details.