COOKBOOK(手册) - CRUD 示例

优质
小牛编辑
129浏览
2023-12-01

title: CRUD
url: /cookbook/crud
menu:
side:
parent: cookbook

  1. weight: 3

CRUD 示例

服务端

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "strconv"
  5. "github.com/labstack/echo"
  6. "github.com/labstack/echo/middleware"
  7. )
  8. type (
  9. user struct {
  10. ID int `json:"id"`
  11. Name string `json:"name"`
  12. }
  13. )
  14. var (
  15. users = map[int]*user{}
  16. seq = 1
  17. )
  18. //----------
  19. // Handlers
  20. //----------
  21. func createUser(c echo.Context) error {
  22. u := &user{
  23. ID: seq,
  24. }
  25. if err := c.Bind(u); err != nil {
  26. return err
  27. }
  28. users[u.ID] = u
  29. seq++
  30. return c.JSON(http.StatusCreated, u)
  31. }
  32. func getUser(c echo.Context) error {
  33. id, _ := strconv.Atoi(c.Param("id"))
  34. return c.JSON(http.StatusOK, users[id])
  35. }
  36. func updateUser(c echo.Context) error {
  37. u := new(user)
  38. if err := c.Bind(u); err != nil {
  39. return err
  40. }
  41. id, _ := strconv.Atoi(c.Param("id"))
  42. users[id].Name = u.Name
  43. return c.JSON(http.StatusOK, users[id])
  44. }
  45. func deleteUser(c echo.Context) error {
  46. id, _ := strconv.Atoi(c.Param("id"))
  47. delete(users, id)
  48. return c.NoContent(http.StatusNoContent)
  49. }
  50. func main() {
  51. e := echo.New()
  52. // Middleware
  53. e.Use(middleware.Logger())
  54. e.Use(middleware.Recover())
  55. // Routes
  56. e.POST("/users", createUser)
  57. e.GET("/users/:id", getUser)
  58. e.PUT("/users/:id", updateUser)
  59. e.DELETE("/users/:id", deleteUser)
  60. // Start server
  61. e.Logger.Fatal(e.Start(":1323"))
  62. }

客户端

curl

创建 User

  1. curl -X POST \
  2. -H 'Content-Type: application/json' \
  3. -d '{"name":"Joe Smith"}' \
  4. localhost:1323/users

Response

  1. {
  2. "id": 1,
  3. "name": "Joe Smith"
  4. }

获取 User

  1. curl localhost:1323/users/1

Response

  1. {
  2. "id": 1,
  3. "name": "Joe Smith"
  4. }

更新 User

  1. curl -X PUT \
  2. -H 'Content-Type: application/json' \
  3. -d '{"name":"Joe"}' \
  4. localhost:1323/users/1

Response

  1. {
  2. "id": 1,
  3. "name": "Joe"
  4. }

删除 User

  1. curl -X DELETE localhost:1323/users/1

Response

NoContent - 204