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"))
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?