Created
June 13, 2018 23:13
-
-
Save Tethik/ef55db82e82fc662262245949593deea to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"net/http" | |
"github.com/labstack/echo" | |
"github.com/labstack/echo/middleware" | |
"github.com/labstack/gommon/log" | |
validator "gopkg.in/go-playground/validator.v9" | |
) | |
type ( | |
// Validator custom validator function to validate incoming json structs. | |
Validator struct { | |
validator *validator.Validate | |
} | |
) | |
// Validate incoming json forms. See: http://gopkg.in/go-playground/validator.v9 | |
func (cv *Validator) Validate(i interface{}) error { | |
err := cv.validator.Struct(i) | |
if err != nil { | |
return echo.NewHTTPError(400, err.Error()) | |
} | |
return nil | |
} | |
type RegisterForm struct { | |
Email string `json:"email" validate:"email"` | |
Password string `json:"password" validate:"required"` | |
} | |
func main() { | |
// Echo instance | |
e := echo.New() | |
e.Binder = &echo.ValidateBinder{} | |
e.Validator = &Validator{validator: validator.New()} | |
// Middleware | |
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ | |
Format: "${method} ${uri} ${status} ${latency_human}\n", | |
})) | |
e.Use(middleware.Recover()) | |
if l, ok := e.Logger.(*log.Logger); ok { | |
l.SetHeader("${time_rfc3339} ${level}") | |
} | |
// Routes | |
e.POST("/", register) | |
// Start server | |
e.Logger.Fatal(e.Start(":1323")) | |
} | |
// Handler | |
func register(c echo.Context) error { | |
var form RegisterForm | |
if err := c.Bind(&form); err != nil { | |
return err | |
} | |
return c.String(http.StatusOK, fmt.Sprintf("Registered %s!", form.Email)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment