-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
64 lines (52 loc) · 1.55 KB
/
server.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package api
import (
"fmt"
db "db.sqlc.dev/app/db/sqlc"
"db.sqlc.dev/app/token"
"db.sqlc.dev/app/utils"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
// Serves HTTP request for our services
// Server serves HTTP requests for our banking service.
type Server struct {
config utils.Config
tokenMaker token.Maker
store db.Store
router *gin.Engine
}
func NewServer(config utils.Config, store db.Store) (*Server, error) {
tokenMaker, err := token.NewPasetoMaker(config.TokenSymmetricKey)
if err != nil {
return nil, fmt.Errorf("cannot create token maker: %w", err)
}
server := &Server{
config: config,
store: store,
tokenMaker: tokenMaker,
}
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("currency", validCurrency)
}
server.setupRouter()
return server, nil
}
func (server *Server) setupRouter() {
router := gin.Default()
router.POST("/users", server.createUser)
router.POST("/users/login", server.loginUser)
authRoutes := router.Group("/").Use(authMiddleware(server.tokenMaker))
authRoutes.POST("/accounts", server.createAccount)
authRoutes.GET("/accounts/:id", server.getAccount)
authRoutes.GET("/accounts", server.listAccounts)
authRoutes.POST("/transfers", server.createTransfer)
server.router = router
}
// run the Http server on a specific address
func (server *Server) Start(address string) error {
return server.router.Run(address)
}
func errorResponse(err error) gin.H {
return gin.H{"error": err.Error()}
}