Quick Start
Quick Start
Section titled “Quick Start”Get up and running with Fox in just a few minutes.
Prerequisites
Section titled “Prerequisites”- Go 1.21 or higher
- Basic familiarity with Go and web development
Installation
Section titled “Installation”go get -u github.com/fox-gonic/foxYour First Fox Application
Section titled “Your First Fox Application”Create a new file main.go:
package main
import ( "github.com/fox-gonic/fox")
type HelloRequest struct { Name string `form:"name" binding:"required"`}
func main() { // Create a Fox router with default middleware r := fox.Default()
// Define a simple GET endpoint with automatic parameter binding r.GET("/hello", func(req *HelloRequest) (any, error) { return map[string]string{ "message": "Hello, " + req.Name + "!", }, nil })
// Define a JSON POST endpoint type CreateUserRequest struct { Name string `json:"name" binding:"required"` Email string `json:"email" binding:"required,email"` }
r.POST("/users", func(req *CreateUserRequest) (any, error) { // In a real application, you would save to a database here return map[string]any{ "id": 1, "name": req.Name, "email": req.Email, }, nil })
// Start the server r.Run(":8080")}Run Your Application
Section titled “Run Your Application”go run main.goTest Your Endpoints
Section titled “Test Your Endpoints”Test the GET endpoint:
curl "http://localhost:8080/hello?name=World"Response:
{ "message": "Hello, World!"}Test the POST endpoint:
curl -X POST http://localhost:8080/users \ -H "Content-Type: application/json" \ -d '{"name":"John Doe","email":"john@example.com"}'Response:
{ "id": 1, "name": "John Doe", "email": "john@example.com"}What’s Next?
Section titled “What’s Next?”Now that you have a basic Fox application running, explore more features:
- Parameter Binding - Learn about different binding options
- Multi-Domain Routing - Route by domain name
- Structured Logging - Add comprehensive logging
- Validation - Custom validation rules
Common Patterns
Section titled “Common Patterns”Error Handling
Section titled “Error Handling”r.GET("/user/:id", func(id int) (*User, error) { user, err := db.GetUser(id) if err != nil { return nil, err // Fox handles error responses automatically } return user, nil})Using Gin Context
Section titled “Using Gin Context”When you need access to the underlying Gin context:
r.GET("/example", func(c *gin.Context, req *Request) (any, error) { // Access Gin context directly userAgent := c.GetHeader("User-Agent")
// Your logic here return response, nil})Custom Validation
Section titled “Custom Validation”type SignupRequest struct { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"`}
func (r *SignupRequest) IsValid() error { if len(r.Password) < 8 { return errors.New("password must be at least 8 characters") } return nil}