forked from techschool/simplebank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
67 lines (53 loc) · 1.69 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
65
66
67
package api
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
db "github.com/techschool/simplebank/db/sqlc"
"github.com/techschool/simplebank/token"
"github.com/techschool/simplebank/util"
)
// Server serves HTTP requests for our banking service.
type Server struct {
config util.Config
store db.Store
tokenMaker token.Maker
router *gin.Engine
}
// NewServer creates a new HTTP server and set up routing.
func NewServer(config util.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)
router.POST("/tokens/renew_access", server.renewAccessToken)
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
}
// Start runs 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()}
}