-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
35 lines (30 loc) · 994 Bytes
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package auth
import (
"github.com/donaderoyan/go-rest-api-boilerplate/internal/errors"
"github.com/donaderoyan/go-rest-api-boilerplate/pkg/log"
routing "github.com/go-ozzo/ozzo-routing/v2"
)
// RegisterHandlers registers handlers for different HTTP requests.
func RegisterHandlers(rg *routing.RouteGroup, service Service, logger log.Logger) {
rg.Post("/login", login(service, logger))
}
// login returns a handler that handles user login request.
func login(service Service, logger log.Logger) routing.Handler {
return func(c *routing.Context) error {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.Read(&req); err != nil {
logger.With(c.Request.Context()).Errorf("invalid request: %v", err)
return errors.BadRequest("")
}
token, err := service.Login(c.Request.Context(), req.Username, req.Password)
if err != nil {
return err
}
return c.Write(struct {
Token string `json:"token"`
}{token})
}
}