Created
August 8, 2020 08:31
-
-
Save mmitou/a9559f12fa8c9df4ff531ba34ee314b0 to your computer and use it in GitHub Desktop.
echo example: bind path param using struct tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "log" | |
| "net/http" | |
| "reflect" | |
| "github.com/labstack/echo/v4" | |
| ) | |
| type Employee struct { | |
| MemberId string `query:"memberId"` | |
| ActivityType string `query:"activityType"` | |
| BusinessUnitCode int `query:"businessUnitCode"` | |
| } | |
| type Point struct { | |
| Name string `param:"name"` | |
| Printable bool `query:"Printable"` | |
| Values []int `query:"values"` | |
| } | |
| func GetEmployee(c echo.Context) error { | |
| var employee Employee | |
| if err := c.Bind(&employee); err != nil { | |
| return err | |
| } | |
| return c.JSON(http.StatusOK, employee) | |
| } | |
| func GetPoint(c echo.Context) error { | |
| var point Point | |
| if err := c.Bind(&point); err != nil { | |
| return err | |
| } | |
| return c.JSON(http.StatusOK, point) | |
| } | |
| func GenHandler(i interface{}) echo.HandlerFunc { | |
| t := reflect.TypeOf(i) | |
| return func(c echo.Context) error { | |
| v := reflect.New(t).Interface() | |
| if err := c.Bind(v); err != nil { | |
| return err | |
| } | |
| return c.JSON(http.StatusOK, v) | |
| } | |
| } | |
| func main() { | |
| e := echo.New() | |
| e.GET("/employee", GenHandler(Employee{})) | |
| e.GET("/point/:name", GenHandler(Point{})) | |
| log.Fatal(e.Start(":8080")) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment