CRUD
一个由内存 store 支撑的完整 CRUD(create, read, update, delete)API。每个处理函数都会把 JSON 请求体绑定到 struct,在锁保护下修改 store,并以 JSON 返回结果。
package main
import ( "context" "net/http" "strconv" "sync"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5/middleware")
type ( user struct { ID int `json:"id"` Name string `json:"name"` })
var ( users = map[int]*user{} seq = 1 lock = sync.Mutex{})
//----------// Handlers//----------
func createUser(c *echo.Context) error { lock.Lock() defer lock.Unlock() u := &user{ ID: seq, } if err := c.Bind(u); err != nil { return err } users[u.ID] = u seq++ return c.JSON(http.StatusCreated, u)}
func getUser(c *echo.Context) error { lock.Lock() defer lock.Unlock() id, _ := strconv.Atoi(c.Param("id")) return c.JSON(http.StatusOK, users[id])}
func updateUser(c *echo.Context) error { lock.Lock() defer lock.Unlock() u := new(user) if err := c.Bind(u); err != nil { return err } id, _ := strconv.Atoi(c.Param("id")) users[id].Name = u.Name return c.JSON(http.StatusOK, users[id])}
func deleteUser(c *echo.Context) error { lock.Lock() defer lock.Unlock() id, _ := strconv.Atoi(c.Param("id")) delete(users, id) return c.NoContent(http.StatusNoContent)}
func getAllUsers(c *echo.Context) error { lock.Lock() defer lock.Unlock() return c.JSON(http.StatusOK, users)}
func main() { e := echo.New()
// Middleware e.Use(middleware.RequestLogger()) e.Use(middleware.Recover())
// Routes e.GET("/users", getAllUsers) e.POST("/users", createUser) e.GET("/users/:id", getUser) e.PUT("/users/:id", updateUser) e.DELETE("/users/:id", deleteUser)
// Start server sc := echo.StartConfig{Address: ":1323"} if err := sc.Start(context.Background(), e); err != nil { e.Logger.Error("failed to start server", "error", err) }}请求:
curl -X POST \ -H 'Content-Type: application/json' \ -d '{"name":"Joe Smith"}' \ localhost:1323/users响应:
{ "id": 1, "name": "Joe Smith"}请求:
curl localhost:1323/users/1响应:
{ "id": 1, "name": "Joe Smith"}请求:
curl -X PUT \ -H 'Content-Type: application/json' \ -d '{"name":"Joe"}' \ localhost:1323/users/1响应:
{ "id": 1, "name": "Joe"}请求:
curl -X DELETE localhost:1323/users/1响应:204 No Content。