Use the Echo framework to initialize a server, define routes with HTTP methods, and attach handler functions that process requests and return JSON responses. Echo provides built-in middleware for logging, CORS, and recovery, making it ideal for production-ready APIs.
Here is a minimal example of a REST API with a GET endpoint and a POST endpoint for creating users:
package main
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var users = []User{{ID: 1, Name: "Alice"}}
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
// Routes
e.GET("/users", getUsers)
e.POST("/users", createUser)
// Start server
e.Logger.Fatal(e.Start(":8080"))
}
func getUsers(c echo.Context) error {
return c.JSON(http.StatusOK, users)
}
func createUser(c echo.Context) error {
var u User
if err := c.Bind(&u); err != nil {
return err
}
u.ID = len(users) + 1
users = append(users, u)
return c.JSON(http.StatusCreated, u)
}
To run this, first install Echo:
go get github.com/labstack/echo/v4
Then run the server:
go run main.go
Test the endpoints with curl:
# Get all users
curl http://localhost:8080/users
# Create a new user
curl -X POST http://localhost:8080/users \
-H "Content-Type: application/json" \
-d '{"name": "Bob"}'
For larger projects, organize routes in a separate file using e.Group() to prefix paths and apply middleware selectively. Echoβs context object gives you easy access to request parameters, query strings, and form data, while its error handling middleware ensures panics donβt crash the server.