http2struct is a lightweight, zero-dependency Go library that simplifies HTTP request processing by allowing you to easily transfer data from HTTP requests directly into Go structs. The library handles data from multiple sources including headers, URL query parameters, path parameters, form data, file uploads, and JSON body.
This streamlined approach to request binding eliminates boilerplate code and helps you write more readable, maintainable, and error-resistant applications.
- Zero Dependencies: Built using only Go's standard library
- Single Function API: Converts an HTTP request to a struct with a single function call
- Comprehensive Source Support:
- JSON body data (
jsontag) - Form data (
formtag) - URL query parameters (
querytag) - Path parameters (
pathtag) - HTTP headers (
headertag) - File uploads - both multipart form (
filetag) and binary (file:"binary"tag)
- JSON body data (
- Automatic Type Conversion: Handles conversion to various Go types:
- Boolean:
bool - Integers:
int,int8,int16,int32,int64 - Unsigned integers:
uint,uint8,uint16,uint32,uint64,uintptr - Floating point:
float32,float64 - Complex numbers:
complex64,complex128 - Strings:
string - Slices of the above types (comma-separated values are automatically split)
- Boolean:
- File Upload Handling: Manages both multipart form files and binary file uploads with the built-in
Filestruct - Extensive Error Reporting: Provides detailed error messages for debugging
- Smart Data Binding: Unlike some other binders, only binds fields with data present in the request, preventing invisible problems
| Benefits | Before (using standard net/http) | After (using emre-onal/http2struct) |
|---|---|---|
| βοΈ Developer Time | π« Expensive (too much parsing code) | π Faster (define the struct and leave parsing to http2struct) |
| β»οΈ Code Repetition | π High | π Lower (eliminates repetitive request parsing code) |
| π Code Readability | π Poor | π€© Highly readable (declarative approach with struct tags) |
| π¨ Maintainability | π‘ Poor | π₯° Highly maintainable (centralized request handling logic) |
| π Error Handling | π Manual for each field | π Comprehensive (detailed errors for debugging) |
| π Type Safety | π¨ Manual type conversion | π Automatic (type-safe conversions with validation) |
go get -u github.com/emre-onal/http2structDefine a struct with appropriate tags and convert your request:
type UserRequest struct {
Name string `json:"name"` // From JSON body
Age int `json:"age"` // From JSON body
Token string `header:"Authorization"` // From request header
Page int `query:"page"` // From URL query parameter
UserID uint64 `path:"user_id"` // From path parameter
Nickname string `form:"nickname"` // From form data
Tags []string `query:"tags"` // Handles comma-separated values
Avatar File `file:"avatar"` // File upload from multipart form
}
func handler(w http.ResponseWriter, r *http.Request) {
var req UserRequest
if err := http2struct.Convert(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Now req is populated with data from the request
fmt.Fprintf(w, "Hello, %s!", req.Name)
}http2struct provides a built-in File struct for handling file uploads:
type File struct {
Name string // Original filename
Size int64 // File size in bytes
Content []byte // File content
}type UploadRequest struct {
// As a value
Avatar File `file:"avatar"`
// Or as a pointer
Document *File `file:"document"`
}type BinaryUploadRequest struct {
// Use the special "binary" tag value
File File `file:"binary"`
// Additional metadata can come from headers
ContentType string `header:"Content-Type"`
Filename string `header:"X-Filename"`
}http2struct allows you to combine data from multiple sources in a single request:
type ComplexRequest struct {
// User data from JSON body
User struct {
Name string `json:"name"`
Email string `json:"email"`
} `json:"user"`
// Configuration from query parameters
Page int `query:"page"`
Limit int `query:"limit"`
// Authentication from headers
Token string `header:"Authorization"`
// Resource identifier from path
ID uint64 `path:"id"`
// File uploads
Avatar File `file:"avatar"`
}The Convert function returns detailed errors to help diagnose issues:
err := http2struct.Convert(r, &req)
if err != nil {
// Handle the error
log.Printf("Request conversion error: %v", err)
http.Error(w, "Bad request format", http.StatusBadRequest)
return
}Error messages are descriptive, indicating:
- Invalid destination types
- Field conversion failures
- Unsupported types
- Form parsing errors
- JSON decoding issues
- Validate Input Data: While
http2structhandles conversion, you should still validate the business logic of the data - Use Appropriate Types: Choose struct field types that match the expected data to avoid conversion errors
- Consider Performance: For large file uploads, process files directly rather than loading them all into memory
- Set Default Values: Initialize struct fields with default values before conversion for optional parameters
| Feature | http2struct | gorilla/schema | gin binding |
|---|---|---|---|
| Zero Dependencies | β | β | β |
| JSON Body Support | β | β | β |
| Form Data Support | β | β | β |
| Query Parameter Support | β | β | β |
| Path Parameter Support | β | β | β |
| Header Support | β | β | β |
| File Upload Support | β | β | β |
| Binary File Support | β | β | β |
| Detailed Error Messages | β | β | β |
Contributions to improve http2struct are welcome! Here's how you can contribute:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
A: Yes, the library works with any framework that uses the standard net/http.Request object, including Gin, Echo, Chi, etc.
A: For query parameters, path parameters, headers, and form values, comma-separated strings are automatically split and converted to slices of the appropriate type.
A: The library will return a detailed error explaining which field failed conversion and why.
A: Yes, JSON body data can be mapped to nested structs. Other sources (query, path, header, form) work with flat structures.