package main
import "github.com/go-mizu/mizu"
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// Input struct for creating users
type CreateUserInput struct {
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
app := mizu.New()
app.Get("/users", listUsers)
app.Get("/users/{id}", getUser)
app.Post("/users", createUser)
app.Listen(":3000")
}
func listUsers(c *mizu.Ctx) error {
users := []User{{ID: "1", Name: "Alice"}}
return c.JSON(200, users)
}
func getUser(c *mizu.Ctx) error {
id := c.Param("id")
return c.JSON(200, User{ID: id, Name: "Alice"})
}
func createUser(c *mizu.Ctx) error {
var input CreateUserInput
// BindJSON parses the request body into the struct
// 1<<20 is the max size (1MB) - prevents huge payloads
if err := c.BindJSON(&input, 1<<20); err != nil {
// Return 400 Bad Request if parsing fails
return c.JSON(400, map[string]string{"error": err.Error()})
}
// Validate the input
if input.Name == "" {
return c.JSON(400, map[string]string{"error": "name is required"})
}
// In a real app, you'd save to a database here
user := User{
ID: "123", // Would be generated
Name: input.Name,
Email: input.Email,
}
// Return 201 Created with the new user
return c.JSON(201, user)
}