Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created August 8, 2020 08:31
Show Gist options
  • Select an option

  • Save mmitou/a9559f12fa8c9df4ff531ba34ee314b0 to your computer and use it in GitHub Desktop.

Select an option

Save mmitou/a9559f12fa8c9df4ff531ba34ee314b0 to your computer and use it in GitHub Desktop.
echo example: bind path param using struct tag
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