Skip to content

Commit

Permalink
Create context
Browse files Browse the repository at this point in the history
  • Loading branch information
ybkuroki committed Dec 26, 2020
1 parent c2e59d4 commit 1bbf94b
Show file tree
Hide file tree
Showing 27 changed files with 318 additions and 282 deletions.
25 changes: 4 additions & 21 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,31 +49,14 @@ const (
DOC = "docker"
)

var config *Config
var env *string

// Load reads the settings written to the yml file
func Load() {
env = flag.String("env", "develop", "To switch configurations.")
func Load() (*Config, string) {
env := flag.String("env", "develop", "To switch configurations.")
flag.Parse()
config = &Config{}
config := &Config{}
if err := configor.Load(config, "application."+*env+".yml"); err != nil {
fmt.Printf("Failed to read application.%s.yml: %s", *env, err)
os.Exit(2)
}
}

// GetConfig returns the configuration data.
func GetConfig() *Config {
return config
}

// SetConfig sets configuration data.
func SetConfig(conf *Config) {
config = conf
}

// GetEnv returns the environment variable.
func GetEnv() *string {
return env
return config, *env
}
10 changes: 5 additions & 5 deletions controller/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/ybkuroki/go-webapp-sample/config"
"github.com/ybkuroki/go-webapp-sample/model"
"github.com/ybkuroki/go-webapp-sample/mycontext"
"github.com/ybkuroki/go-webapp-sample/service"
"github.com/ybkuroki/go-webapp-sample/session"
)
Expand All @@ -20,24 +20,24 @@ func GetLoginStatus() echo.HandlerFunc {
}

// GetLoginAccount returns the account data of logged in user.
func GetLoginAccount() echo.HandlerFunc {
func GetLoginAccount(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
if !config.GetConfig().Extension.SecurityEnabled {
if !context.GetConfig().Extension.SecurityEnabled {
return c.JSON(http.StatusOK, dummyAccount)
}
return c.JSON(http.StatusOK, session.GetAccount(c))
}
}

// PostLogin is the method to login using username and password by http post.
func PostLogin() echo.HandlerFunc {
func PostLogin(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")

account := session.GetAccount(c)
if account == nil {
authenticate, a := service.AuthenticateByUsernameAndPassword(username, password)
authenticate, a := service.AuthenticateByUsernameAndPassword(context, username, password)
if authenticate {
_ = session.SetAccount(c, a)
_ = session.Save(c)
Expand Down
6 changes: 3 additions & 3 deletions controller/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

func TestGetLoginStatus(t *testing.T) {
router := test.Prepare()
router, _ := test.Prepare()
router.GET(APIAccountLoginStatus, GetLoginStatus())

req := httptest.NewRequest("GET", APIAccountLoginStatus, nil)
Expand All @@ -24,8 +24,8 @@ func TestGetLoginStatus(t *testing.T) {
}

func TestGetLoginAccount(t *testing.T) {
router := test.Prepare()
router.GET(APIAccountLoginAccount, GetLoginAccount())
router, context := test.Prepare()
router.GET(APIAccountLoginAccount, GetLoginAccount(context))

req := httptest.NewRequest("GET", APIAccountLoginAccount, nil)
rec := httptest.NewRecorder()
Expand Down
21 changes: 11 additions & 10 deletions controller/book.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,39 @@ import (

"github.com/labstack/echo/v4"
"github.com/ybkuroki/go-webapp-sample/model/dto"
"github.com/ybkuroki/go-webapp-sample/mycontext"
"github.com/ybkuroki/go-webapp-sample/service"
)

// GetBookList returns the list of all books.
func GetBookList() echo.HandlerFunc {
func GetBookList(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
page, _ := strconv.Atoi(c.QueryParam("page"))
size, _ := strconv.Atoi(c.QueryParam("size"))

return c.JSON(http.StatusOK, service.FindAllBooksByPage(page, size))
return c.JSON(http.StatusOK, service.FindAllBooksByPage(context, page, size))
}
}

// GetBookSearch returns the list of matched books by searching.
func GetBookSearch() echo.HandlerFunc {
func GetBookSearch(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
title := c.QueryParam("query")
page, _ := strconv.Atoi(c.QueryParam("page"))
size, _ := strconv.Atoi(c.QueryParam("size"))

return c.JSON(http.StatusOK, service.FindBooksByTitle(title, page, size))
return c.JSON(http.StatusOK, service.FindBooksByTitle(context, title, page, size))
}
}

// PostBookRegist register a new book by http post.
func PostBookRegist() echo.HandlerFunc {
func PostBookRegist(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
dto := dto.NewRegBookDto()
if err := c.Bind(dto); err != nil {
return c.JSON(http.StatusBadRequest, dto)
}
book, result := service.RegisterBook(dto)
book, result := service.RegisterBook(context, dto)
if result != nil {
return c.JSON(http.StatusBadRequest, result)
}
Expand All @@ -46,13 +47,13 @@ func PostBookRegist() echo.HandlerFunc {
}

// PostBookEdit edit the existing book by http post.
func PostBookEdit() echo.HandlerFunc {
func PostBookEdit(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
dto := dto.NewChgBookDto()
if err := c.Bind(dto); err != nil {
return c.JSON(http.StatusBadRequest, dto)
}
book, result := service.EditBook(dto)
book, result := service.EditBook(context, dto)
if result != nil {
return c.JSON(http.StatusBadRequest, result)
}
Expand All @@ -61,13 +62,13 @@ func PostBookEdit() echo.HandlerFunc {
}

// PostBookDelete deletes the existing book by http post.
func PostBookDelete() echo.HandlerFunc {
func PostBookDelete(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
dto := dto.NewChgBookDto()
if err := c.Bind(dto); err != nil {
return c.JSON(http.StatusBadRequest, dto)
}
book, result := service.DeleteBook(dto)
book, result := service.DeleteBook(context, dto)
if result != nil {
return c.JSON(http.StatusBadRequest, result)
}
Expand Down
44 changes: 22 additions & 22 deletions controller/book_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import (
"github.com/stretchr/testify/assert"
"github.com/ybkuroki/go-webapp-sample/model"
"github.com/ybkuroki/go-webapp-sample/model/dto"
"github.com/ybkuroki/go-webapp-sample/repository"
"github.com/ybkuroki/go-webapp-sample/mycontext"
"github.com/ybkuroki/go-webapp-sample/test"
)

func TestGetBookList(t *testing.T) {
router := test.Prepare()
router.GET(APIBookList, GetBookList())
router, context := test.Prepare()
router.GET(APIBookList, GetBookList(context))

setUpTestData()
setUpTestData(context)

uri := test.NewRequestBuilder().URL(APIBookList).Params("page", "0").Params("size", "5").Build().GetRequestURL()
req := httptest.NewRequest("GET", uri, nil)
Expand All @@ -26,17 +26,17 @@ func TestGetBookList(t *testing.T) {
router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindAllByPage(repository.GetRepository(), 0, 5)
data, _ := book.FindAllByPage(context.GetRepository(), 0, 5)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestGetBookSearch(t *testing.T) {
router := test.Prepare()
router.GET(APIBookSearch, GetBookSearch())
router, context := test.Prepare()
router.GET(APIBookSearch, GetBookSearch(context))

setUpTestData()
setUpTestData(context)

uri := test.NewRequestBuilder().URL(APIBookSearch).Params("query", "Test").Params("page", "0").Params("size", "5").Build().GetRequestURL()
req := httptest.NewRequest("GET", uri, nil)
Expand All @@ -45,15 +45,15 @@ func TestGetBookSearch(t *testing.T) {
router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByTitle(repository.GetRepository(), "Test", 0, 5)
data, _ := book.FindByTitle(context.GetRepository(), "Test", 0, 5)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookRegist(t *testing.T) {
router := test.Prepare()
router.POST(APIBookRegist, PostBookRegist())
router, context := test.Prepare()
router.POST(APIBookRegist, PostBookRegist(context))

param := createRegDto()
req := httptest.NewRequest("POST", APIBookRegist, strings.NewReader(test.ConvertToString(param)))
Expand All @@ -64,17 +64,17 @@ func TestPostBookRegist(t *testing.T) {
router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)
data, _ := book.FindByID(context.GetRepository(), 1)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookEdit(t *testing.T) {
router := test.Prepare()
router.POST(APIBookEdit, PostBookEdit())
router, context := test.Prepare()
router.POST(APIBookEdit, PostBookEdit(context))

setUpTestData()
setUpTestData(context)

param := createChgDto()
req := httptest.NewRequest("POST", APIBookEdit, strings.NewReader(test.ConvertToString(param)))
Expand All @@ -85,20 +85,20 @@ func TestPostBookEdit(t *testing.T) {
router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)
data, _ := book.FindByID(context.GetRepository(), 1)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookDelete(t *testing.T) {
router := test.Prepare()
router.POST(APIBookDelete, PostBookDelete())
router, context := test.Prepare()
router.POST(APIBookDelete, PostBookDelete(context))

setUpTestData()
setUpTestData(context)

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)
data, _ := book.FindByID(context.GetRepository(), 1)

param := createChgDto()
req := httptest.NewRequest("POST", APIBookDelete, strings.NewReader(test.ConvertToString(param)))
Expand All @@ -112,9 +112,9 @@ func TestPostBookDelete(t *testing.T) {
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func setUpTestData() {
func setUpTestData(context mycontext.Context) {
model := model.NewBook("Test1", "123-123-123-1", 1, 1)
repo := repository.GetRepository()
repo := context.GetRepository()
_, _ = model.Create(repo)
}

Expand Down
5 changes: 2 additions & 3 deletions controller/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/ybkuroki/go-webapp-sample/logger"
)

// APIError represents
Expand Down Expand Up @@ -32,8 +31,8 @@ func JSONErrorHandler(err error, c echo.Context) {

if !c.Response().Committed {
if reserr := c.JSON(code, apierr); reserr != nil {
logger.GetZapLogger().Errorf(reserr.Error())
//logger.GetZapLogger().Errorf(reserr.Error())
}
}
logger.GetZapLogger().Debugf(err.Error())
//logger.GetZapLogger().Debugf(err.Error())
}
2 changes: 1 addition & 1 deletion controller/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func TestGetHealthCheck(t *testing.T) {
router := test.Prepare()
router, _ := test.Prepare()
router.GET(APIHealth, GetHealthCheck())

req := httptest.NewRequest("GET", APIHealth, nil)
Expand Down
9 changes: 5 additions & 4 deletions controller/master.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@ import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/ybkuroki/go-webapp-sample/mycontext"
"github.com/ybkuroki/go-webapp-sample/service"
)

// GetCategoryList returns the list of all categories.
func GetCategoryList() echo.HandlerFunc {
func GetCategoryList(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
return c.JSON(http.StatusOK, service.FindAllCategories())
return c.JSON(http.StatusOK, service.FindAllCategories(context))
}
}

// GetFormatList returns the list of all formats.
func GetFormatList() echo.HandlerFunc {
func GetFormatList(context mycontext.Context) echo.HandlerFunc {
return func(c echo.Context) error {
return c.JSON(http.StatusOK, service.FindAllFormats())
return c.JSON(http.StatusOK, service.FindAllFormats(context))
}
}
8 changes: 4 additions & 4 deletions controller/mater_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
)

func TestGetCategoryList(t *testing.T) {
router := test.Prepare()
router.GET(APIMasterCategory, GetCategoryList())
router, context := test.Prepare()
router.GET(APIMasterCategory, GetCategoryList(context))

req := httptest.NewRequest("GET", APIMasterCategory, nil)
rec := httptest.NewRecorder()
Expand All @@ -30,8 +30,8 @@ func TestGetCategoryList(t *testing.T) {
}

func TestGetFormatList(t *testing.T) {
router := test.Prepare()
router.GET(APIMasterFormat, GetFormatList())
router, context := test.Prepare()
router.GET(APIMasterFormat, GetFormatList(context))

req := httptest.NewRequest("GET", APIMasterFormat, nil)
rec := httptest.NewRecorder()
Expand Down
2 changes: 1 addition & 1 deletion logger/gormlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func (l *Logger) Print(values ...interface{}) {
func (l *Logger) Println(values []interface{}) {
sql := createLog(values)
if sql != "" {
l.zap.Debugf(sql)
l.Zap.Debugf(sql)
}
}

Expand Down
Loading

0 comments on commit 1bbf94b

Please sign in to comment.