Skip to content

Commit 6196885

Browse files
committed
merge router and server to api package
1 parent 06f6451 commit 6196885

15 files changed

+479
-152
lines changed

Makefile

+4-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,7 @@ docker_run:
2828
server:
2929
go run main.go
3030

31-
.PHONY: postgres createdb dropdb migrateup migratedown build test docker_build docker_run server
31+
mock:
32+
mockgen -package mockdb -destination app/repository/mock/store.go github.com/belito3/go-web-api/app/repository/impl IStore
33+
34+
.PHONY: postgres createdb dropdb migrateup migratedown build test docker_build docker_run server mock

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
which mockgen
4444
--> /home/$USER/go/bin/mockgen
4545
```
46+
- Gen mock code: `make mock`
4647

4748
### References
4849
1. [simplebank](https://github.com/techschool/simplebank)

app/api/account.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package service
1+
package api
22

33
import (
44
"fmt"
@@ -8,20 +8,20 @@ import (
88
"net/http"
99
)
1010

11-
type AccountService struct {
11+
type Account struct {
1212
store impl.IStore
1313
}
1414

15-
func NewAccountService(store impl.IStore) *AccountService {
16-
return &AccountService{store: store}
15+
func NewAccount(store impl.IStore) *Account {
16+
return &Account{store: store}
1717
}
1818

1919
type createAccountRequest struct {
2020
Owner string `json:"owner" binding:"required"`
2121
Currency string `json:"currency" binding:"required,oneof=USD EUR"`
2222
}
2323

24-
func (s *AccountService) CreateAccount(c *gin.Context) {
24+
func (s *Account) createAccount(c *gin.Context) {
2525
// Add account
2626
ctx := c.Request.Context()
2727
var req createAccountRequest
@@ -53,7 +53,7 @@ type getAccountRequest struct {
5353
ID int64 `uri:"id" binding:"required,min=1"`
5454
}
5555

56-
func (s *AccountService) GetAccount(c *gin.Context) {
56+
func (s *Account) getAccount(c *gin.Context) {
5757
ctx := c.Request.Context()
5858
var req getAccountRequest
5959
if err := c.ShouldBindUri(&req); err != nil {

app/api/account_test.go

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package api
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
9+
mockdb "github.com/belito3/go-web-api/app/repository/mock"
10+
11+
"github.com/belito3/go-web-api/app/config"
12+
"github.com/belito3/go-web-api/app/repository/impl"
13+
"github.com/belito3/go-web-api/app/util"
14+
"github.com/golang/mock/gomock"
15+
"github.com/stretchr/testify/require"
16+
"go.uber.org/dig"
17+
)
18+
19+
func TestGetAccountAPI(t *testing.T) {
20+
account := randomAccount()
21+
22+
ctrl := gomock.NewController(t)
23+
defer ctrl.Finish()
24+
25+
store := mockdb.NewMockIStore(ctrl)
26+
// build stubs
27+
store.EXPECT().
28+
GetAccount(gomock.Any(), gomock.Eq(account.ID)).
29+
Times(1).
30+
Return(account, nil)
31+
32+
// Build container
33+
container := dig.New()
34+
conf := config.AppConfiguration{}
35+
//// Inject store to container
36+
_ = container.Provide(func() impl.IStore {
37+
return store
38+
})
39+
40+
// start test server and send request
41+
server := NewServer(conf, container)
42+
// Inject api to container
43+
_ = server.InitGinEngine()
44+
45+
recorder := httptest.NewRecorder()
46+
47+
url := fmt.Sprintf("/api/v1/account/%d", account.ID)
48+
request, err := http.NewRequest(http.MethodGet, url, nil)
49+
require.NoError(t, err)
50+
51+
server.router.ServeHTTP(recorder, request)
52+
// check response
53+
require.Equal(t, http.StatusOK, recorder.Code)
54+
}
55+
56+
func randomAccount() impl.Account {
57+
return impl.Account{
58+
ID: util.RandomInt(1, 1000),
59+
Owner: util.RandomOwner(),
60+
Balance: util.RandomMoney(),
61+
Currency: util.RandomCurrency(),
62+
}
63+
}

app/api/authen.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package service
1+
package api
22

33
import (
44
"github.com/belito3/go-web-api/pkg/logger"

app/api/dig.go

+4-8
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
package service
1+
package api
22

3-
import (
4-
"go.uber.org/dig"
5-
)
6-
7-
func Inject(container *dig.Container) error {
8-
_ = container.Provide(NewAccountService)
9-
return nil
3+
func (s *Server) injectAPIHandle() error {
4+
err := s.container.Provide(NewAccount)
5+
return err
106
}

app/api/main_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package api
2+
3+
+7-13
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
package service
1+
package api
22

3-
import (
4-
"github.com/gin-gonic/gin"
5-
)
3+
import "github.com/gin-gonic/gin"
64

75
/*
86
error
@@ -13,7 +11,6 @@ error
1311
}
1412
*/
1513

16-
1714
/*
1815
success
1916
{
@@ -27,13 +24,12 @@ success
2724
}
2825
*/
2926

30-
3127
type ResultSuccess struct {
32-
OK bool `json:"ok"`
28+
OK bool `json:"ok"`
3329
Result map[string]interface{} `json:"result"`
3430
}
3531

36-
func ResponseSuccess(c *gin.Context, statusCode int, result map[string]interface{}){
32+
func responseSuccess(c *gin.Context, statusCode int, result map[string]interface{}) {
3733
rs := ResultSuccess{
3834
OK: true,
3935
Result: result,
@@ -42,12 +38,10 @@ func ResponseSuccess(c *gin.Context, statusCode int, result map[string]interface
4238
}
4339

4440
// responseError
45-
func ResponseError(c *gin.Context, statusCode int, description string){
41+
func responseError(c *gin.Context, statusCode int, description string) {
4642
c.JSON(statusCode, gin.H{
47-
"ok": false,
48-
"error": statusCode,
43+
"ok": false,
44+
"error": statusCode,
4945
"description": description,
5046
})
5147
}
52-
53-

app/api/s_router.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package api
2+
3+
// ApplyRoutes applies router to gin Router
4+
func (s *Server) applyRoutes() error {
5+
return s.container.Invoke(func(
6+
sAccount *Account,
7+
) error {
8+
g := s.router.Group("/api/")
9+
v1 := g.Group("/v1")
10+
{
11+
v1.POST("/signin", Signin)
12+
//v1.Use(api.TokenAuthMiddleware())
13+
account := v1.Group("/account")
14+
{
15+
account.POST("/add", sAccount.createAccount)
16+
account.GET("/:id", sAccount.getAccount)
17+
}
18+
}
19+
return nil
20+
})
21+
}
+31-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package route
1+
package api
22

33
import (
44
"github.com/belito3/go-web-api/app/config"
@@ -7,13 +7,23 @@ import (
77
"go.uber.org/dig"
88
)
99

10-
func InitGinEngine(container *dig.Container, conf config.AppConfiguration) *gin.Engine {
11-
gin.SetMode(conf.RunMode)
10+
// Server service HTTP requests for our banking service
11+
type Server struct {
12+
conf config.AppConfiguration
13+
container *dig.Container
14+
router *gin.Engine
15+
}
16+
17+
func NewServer(conf config.AppConfiguration, container *dig.Container) *Server {
18+
return &Server{conf: conf, container: container}
19+
}
20+
21+
func (s *Server) InitGinEngine() *gin.Engine {
22+
gin.SetMode(s.conf.RunMode)
1223

1324
//app := gin.Default()
1425
app := gin.New()
1526

16-
1727
// Add a logger middleware, which:
1828
// - Logs all requests, like a combined access and error log.
1929
// - Logs to stderr.
@@ -23,10 +33,10 @@ func InitGinEngine(container *dig.Container, conf config.AppConfiguration) *gin.
2333
app.NoRoute(middleware.NoRouteHandler())
2434

2535
// rate_limit per client
26-
app.Use(middleware.CRateLimiterMiddleware(conf))
36+
app.Use(middleware.CRateLimiterMiddleware(s.conf))
2737

2838
// rate_limit per app
29-
app.Use(middleware.ARateLimiterMiddleware(conf))
39+
app.Use(middleware.ARateLimiterMiddleware(s.conf))
3040

3141
app.GET("/", func(c *gin.Context) {
3242
c.JSON(200, gin.H{
@@ -36,14 +46,25 @@ func InitGinEngine(container *dig.Container, conf config.AppConfiguration) *gin.
3646

3747
// CORS
3848
app.Use(middleware.CORSMiddleware())
39-
49+
s.router = app
4050

4151
// Router register
42-
_ = ApplyRoutes(app, container)
52+
err := s.injectAPIHandle()
53+
handleError(err)
54+
55+
err = s.applyRoutes()
56+
handleError(err)
4357

4458
// Swagger:
4559

4660
// Website:
47-
4861
return app
49-
}
62+
}
63+
64+
func handleError(err error) {
65+
if err != nil {
66+
panic(err)
67+
}
68+
}
69+
70+

0 commit comments

Comments
 (0)