()
| 38 | ) |
| 39 | |
| 40 | func main() { |
| 41 | // Initialize sample data |
| 42 | users[1] = &User{ID: 1, Name: "Alice", Email: "alice@example.com"} |
| 43 | users[2] = &User{ID: 2, Name: "Bob", Email: "bob@example.com"} |
| 44 | nextID = 3 |
| 45 | |
| 46 | // Create DotWeb app |
| 47 | app := dotweb.New() |
| 48 | app.SetDevelopmentMode() |
| 49 | |
| 50 | // Global error handler |
| 51 | app.SetExceptionHandle(func(ctx dotweb.Context, err error) { |
| 52 | ctx.Response().SetContentType(dotweb.MIMEApplicationJSONCharsetUTF8) |
| 53 | ctx.WriteJsonC(500, ErrorResponse{Error: err.Error()}) |
| 54 | }) |
| 55 | |
| 56 | // 404 handler |
| 57 | app.SetNotFoundHandle(func(ctx dotweb.Context) { |
| 58 | ctx.Response().SetContentType(dotweb.MIMEApplicationJSONCharsetUTF8) |
| 59 | ctx.WriteJsonC(404, ErrorResponse{Error: "Not found"}) |
| 60 | }) |
| 61 | |
| 62 | // API group |
| 63 | api := app.HttpServer.Group("/api") |
| 64 | |
| 65 | // ===== User CRUD ===== |
| 66 | |
| 67 | // GET /api/users - List all users |
| 68 | api.GET("/users", listUsers) |
| 69 | |
| 70 | // GET /api/users/:id - Get user by ID |
| 71 | api.GET("/users/:id", getUser) |
| 72 | |
| 73 | // POST /api/users - Create user |
| 74 | api.POST("/users", createUser) |
| 75 | |
| 76 | // PUT /api/users/:id - Update user |
| 77 | api.PUT("/users/:id", updateUser) |
| 78 | |
| 79 | // DELETE /api/users/:id - Delete user |
| 80 | api.DELETE("/users/:id", deleteUser) |
| 81 | |
| 82 | // Health check |
| 83 | api.GET("/health", func(ctx dotweb.Context) error { |
| 84 | ctx.Response().Header().Set("Content-Type", "application/json") |
| 85 | return ctx.WriteString(`{"status": "ok"}`) |
| 86 | }) |
| 87 | |
| 88 | fmt.Println("🚀 JSON API running at http://localhost:8080") |
| 89 | fmt.Println("\nAPI Endpoints:") |
| 90 | fmt.Println(" GET /api/health - Health check") |
| 91 | fmt.Println(" GET /api/users - List all users") |
| 92 | fmt.Println(" GET /api/users/:id - Get user by ID") |
| 93 | fmt.Println(" POST /api/users - Create user") |
| 94 | fmt.Println(" PUT /api/users/:id - Update user") |
| 95 | fmt.Println(" DELETE /api/users/:id - Delete user") |
| 96 | |
| 97 | if err := app.StartServer(8080); err != nil { |
nothing calls this directly
no test coverage detected