func getUser(c echo.Context) error { userID := c.Param("id") user, err := getUserByID(userID) if err != nil { return c.JSON(http.StatusNotFound, map[string]string{"message": "user not found"}) } return c.JSON(http.StatusOK, user) }
type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } func createUser(c echo.Context) error { user := new(User) if err := c.Bind(user); err != nil { return c.JSON(http.StatusBadRequest, map[string]string{"message": "invalid request body"}) } if err := saveUser(user); err != nil { return c.JSON(http.StatusInternalServerError, map[string]string{"message": "failed to save user"}) } return c.JSON(http.StatusCreated, user) }This example defines a handler function to create a new user from JSON data. The function receives an echo.Context object and initializes a new User object. It then uses the Bind method to populate the User object from the JSON data in the request body. If the request body is invalid or cannot be bound to the User object, the function returns a JSON response with an error message and HTTP status code 400. If the user cannot be saved (e.g. due to a database error), the function returns a JSON response with an error message and HTTP status code 500. If the user is successfully saved, the function returns a JSON response with the user data and HTTP status code 201. In conclusion, the go github.com.labstack.echo package library is used to build HTTP servers and services using Go, and the Context JSON package provides functionality to convert JSON data to and from Go structures.