How do I build a REST API with Echo in Go?

Building a REST API with Echo in Go is straightforward and efficient. Echo is a high-performance, extensible, minimalist web framework for Go that makes it easy to create web applications and RESTful APIs. Below is a simple example of how to set up a REST API using the Echo framework in Go.

package main import ( "net/http" "github.com/labstack/echo/v4" ) // Define a struct to represent the data type Item struct { ID string `json:"id"` Name string `json:"name"` } // In-memory data store var items = map[string]Item{ "1": {ID: "1", Name: "Item One"}, "2": {ID: "2", Name: "Item Two"}, } // Get Items func getItems(c echo.Context) error { return c.JSON(http.StatusOK, items) } // Get Item by ID func getItem(c echo.Context) error { id := c.Param("id") item, ok := items[id] if !ok { return c.JSON(http.StatusNotFound, map[string]string{"message": "Item not found"}) } return c.JSON(http.StatusOK, item) } // Create Item func createItem(c echo.Context) error { item := Item{} if err := c.Bind(&item); err != nil { return c.JSON(http.StatusBadRequest, map[string]string{"message": "Invalid input"}) } items[item.ID] = item return c.JSON(http.StatusCreated, item) } func main() { e := echo.New() // Define the routes e.GET("/items", getItems) e.GET("/items/:id", getItem) e.POST("/items", createItem) // Start the server e.Logger.Fatal(e.Start(":8080")) }

Go Echo REST API Go web framework Echo framework example building REST API in Go