Skip to content

Commit

Permalink
Merge pull request #112 from abyssparanoia/refactor/http_logger
Browse files Browse the repository at this point in the history
Refactor/http logger
  • Loading branch information
abyssparanoia authored Apr 27, 2020
2 parents d3bcd3f + 362161d commit 07d002c
Show file tree
Hide file tree
Showing 28 changed files with 340 additions and 1,038 deletions.
4 changes: 2 additions & 2 deletions .envrc.tepl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export GOOGLE_APPLICATION_CREDENTIALS="./serviceAccount.json"
export PROJECT_ID="sample"

# default server
export DEFAULT_ENV="LOCAL"
export DEFAULT_ENV="local"
export DEFAULT_PORT="8080"
export DEFAULT_MIN_LOG_SEVERITY="DEBUG"
export DEFAULT_DB_HOST="tcp(localhost:3306)"
Expand All @@ -16,7 +16,7 @@ export DEFAULT_GRPC_ENV="LOCAL"
export DEFAULT_GRPC_PORT="50051"

# push notification server
export PUSH_NOTIFICATION_ENV="LOCAL"
export PUSH_NOTIFICATION_ENV="local"
export PUSH_NOTIFICATION_PORT="8081"
export PUSH_NOTIFICATION_MIN_LOG_SEVERITY="DEBUG"
export FCM_SERVER_KEY=hogehoge
15 changes: 7 additions & 8 deletions cmd/default/dependency.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@ import (
"github.com/abyssparanoia/rapid-go/internal/pkg/gluefirebaseauth"
"github.com/abyssparanoia/rapid-go/internal/pkg/gluemysql"
"github.com/abyssparanoia/rapid-go/internal/pkg/httpheader"
"github.com/abyssparanoia/rapid-go/internal/pkg/log"
"github.com/abyssparanoia/rapid-go/internal/pkg/httpmiddleware"
"github.com/volatiletech/sqlboiler/boil"
"go.uber.org/zap"
)

// Dependency ... dependency
type Dependency struct {
Log *log.Middleware
httpMiddleware *httpmiddleware.HTTPMiddleware
gluefirebaseauth *gluefirebaseauth.Middleware
DummyHTTPHeader *httpheader.Middleware
HTTPHeader *httpheader.Middleware
UserHandler *api.UserHandler
}

// Inject ... indect dependency
func (d *Dependency) Inject(e *environment) {
func (d *Dependency) Inject(e *environment, logger *zap.Logger) {

var lCli log.Writer
var firebaseauth gluefirebaseauth.Firebaseauth

authCli := gluefirebaseauth.NewClient(e.ProjectID)
Expand All @@ -32,12 +32,10 @@ func (d *Dependency) Inject(e *environment) {
// pkg
_ = gluemysql.NewClient(e.DBHost, e.DBUser, e.DBPassword, e.DBDatabase)

if e.Envrionment == "LOCAL" {
lCli = log.NewWriterStdout()
if e.Envrionment == "local" {
firebaseauth = gluefirebaseauth.NewDebug(authCli)
boil.DebugMode = true
} else {
lCli = log.NewWriterStackdriver(e.ProjectID)
firebaseauth = gluefirebaseauth.New(authCli)
}

Expand All @@ -50,7 +48,8 @@ func (d *Dependency) Inject(e *environment) {
uSvc := usecase.NewUser(uRepo)

// Middleware
d.Log = log.NewMiddleware(lCli, e.MinLogSeverity)
d.httpMiddleware = httpmiddleware.New(logger)

d.gluefirebaseauth = gluefirebaseauth.NewMiddleware(firebaseauth)
d.DummyHTTPHeader = httpheader.NewMiddleware(dhh)
d.HTTPHeader = httpheader.NewMiddleware(hh)
Expand Down
21 changes: 14 additions & 7 deletions cmd/default/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"syscall"
"time"

"github.com/abyssparanoia/rapid-go/internal/pkg/log"

"github.com/caarlos0/env/v6"
"github.com/go-chi/chi"
)
Expand All @@ -20,9 +22,14 @@ func main() {
panic(err)
}

logger, err := log.New(e.Envrionment)
if err != nil {
panic(err)
}

// Dependency
d := Dependency{}
d.Inject(e)
d.Inject(e, logger)

// Routing
r := chi.NewRouter()
Expand All @@ -37,26 +44,26 @@ func main() {
}

// Run
fmt.Printf("[START] server. port: %s\n", addr)
logger.Sugar().Debugf("[START] server. port: %s\n", addr)
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
fmt.Printf("[CLOSED] server closed with error: %s\n", err)
logger.Sugar().Debugf("[CLOSED] server closed with error: %s\n", err)
}
}()

// graceful shuttdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
fmt.Printf("SIGNAL %d received, so server shutting down now...\n", <-quit)
logger.Sugar().Debugf("SIGNAL %d received, so server shutting down now...\n", <-quit)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

err := server.Shutdown(ctx)
err = server.Shutdown(ctx)
if err != nil {
fmt.Printf("failed to gracefully shutdown: %s\n", err)
logger.Sugar().Debugf("failed to gracefully shutdown: %s\n", err)
}

fmt.Printf("server shutdown completed\n")
logger.Sugar().Debugf("server shutdown completed\n")

}
2 changes: 1 addition & 1 deletion cmd/default/routing.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func Routing(r chi.Router, d Dependency) {
r.Use(accesscontrol.Handle)

// request log
r.Use(d.Log.Handle)
r.Use(d.httpMiddleware.Handle)

// need to authenticate for production
r.Route("/v1", func(r chi.Router) {
Expand Down
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,20 @@ require (
github.com/kelseyhightower/envconfig v1.4.0
github.com/leodido/go-urn v1.2.0 // indirect
github.com/lib/pq v1.4.0
github.com/opentracing/opentracing-go v1.1.0
github.com/pkg/errors v0.8.0
github.com/rs/xid v1.2.1
github.com/spf13/cobra v1.0.0
github.com/spf13/viper v1.6.3
github.com/uber/jaeger-client-go v2.23.0+incompatible
github.com/uber/jaeger-lib v2.2.0+incompatible // indirect
github.com/unrolled/render v1.0.3
github.com/volatiletech/inflect v0.0.0-20170731032912-e7201282ae8d // indirect
github.com/volatiletech/null v8.0.0+incompatible
github.com/volatiletech/sqlboiler v3.7.0+incompatible
go.uber.org/zap v1.15.0
golang.org/x/text v0.3.2
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543
google.golang.org/api v0.22.0
google.golang.org/grpc v1.29.1
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
Expand Down Expand Up @@ -253,6 +255,10 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/uber/jaeger-client-go v2.23.0+incompatible h1:o2g11IUBdEsSZVzF3k7+bahLmxRP/dbOoW4zQ30UlKE=
github.com/uber/jaeger-client-go v2.23.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.2.0+incompatible h1:MxZXOiR2JuoANZ3J6DE/U0kSFv/eJ/GfSYVCjK7dyaw=
github.com/uber/jaeger-lib v2.2.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/unrolled/render v1.0.2 h1:dGS3EmChQP3yOi1YeFNO/Dx+MbWZhdvhQJTXochM5bs=
github.com/unrolled/render v1.0.2/go.mod h1:gN9T0NhL4Bfbwu8ann7Ry/TGHYfosul+J0obPf6NBdM=
Expand Down
4 changes: 2 additions & 2 deletions internal/default/handler/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ func (h *UserHandler) Get(w http.ResponseWriter, r *http.Request) {

v := validator.New()
if err := v.Struct(param); err != nil {
renderer.HandleError(ctx, w, "validation error: ", err)
renderer.HandleError(ctx, w, err)
return
}

user, err := h.userUsecase.Get(ctx, param.UserID)
if err != nil {
renderer.HandleError(ctx, w, "h.Svc.Get", err)
renderer.HandleError(ctx, w, err)
return
}

Expand Down
35 changes: 0 additions & 35 deletions internal/default/handler/worker/admin.go

This file was deleted.

31 changes: 0 additions & 31 deletions internal/default/handler/worker/sample.go

This file was deleted.

11 changes: 8 additions & 3 deletions internal/default/infrastructure/repository/user_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ package repository
import (
"context"
"database/sql"
"fmt"

"github.com/abyssparanoia/rapid-go/internal/dbmodels/defaultdb"
"github.com/abyssparanoia/rapid-go/internal/default/domain/model"
"github.com/abyssparanoia/rapid-go/internal/default/domain/repository"
"github.com/abyssparanoia/rapid-go/internal/default/infrastructure/entity"
"github.com/abyssparanoia/rapid-go/internal/pkg/gluesqlboiler"
"github.com/abyssparanoia/rapid-go/internal/pkg/httperror"
"github.com/abyssparanoia/rapid-go/internal/pkg/log"
"github.com/pkg/errors"
"go.uber.org/zap"
)

type user struct {
Expand All @@ -23,10 +27,11 @@ func (r *user) Get(ctx context.Context, userID string) (*model.User, error) {

if err != nil {
if err == sql.ErrNoRows {
log.Errorm(ctx, "dbUser.select.not.found", err)
return nil, err
msg := fmt.Sprintf("user %s not found", userID)
err = errors.Wrap(err, msg)
log.Errorf(ctx, msg, zap.Error(err))
return nil, httperror.NotFoundError(err)
}
log.Errorm(ctx, "dbUser.select", err)
return nil, err
}

Expand Down
12 changes: 0 additions & 12 deletions internal/default/usecase/error_message.go

This file was deleted.

5 changes: 2 additions & 3 deletions internal/default/usecase/user_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package usecase

import (
"context"
"errors"

"github.com/abyssparanoia/rapid-go/internal/default/domain/model"
"github.com/abyssparanoia/rapid-go/internal/default/domain/repository"
"github.com/abyssparanoia/rapid-go/internal/pkg/log"
)

type user struct {
Expand All @@ -15,12 +15,11 @@ type user struct {
func (s *user) Get(ctx context.Context, userID string) (*model.User, error) {
user, err := s.userRepo.Get(ctx, userID)
if err != nil {
log.Errorm(ctx, "s.userRepo.Get", err)
return nil, err
}

if !user.Exist() {
return nil, newUserNotExistError(ctx, userID)
return nil, errors.New("not found user")
}

return user, nil
Expand Down
14 changes: 0 additions & 14 deletions internal/pkg/errcode/error.go

This file was deleted.

19 changes: 0 additions & 19 deletions internal/pkg/errcode/model.go

This file was deleted.

10 changes: 10 additions & 0 deletions internal/pkg/httperror/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package httperror

import (
"net/http"
)

// NotFoundError ... not found error
func NotFoundError(err error) *HTTPError {
return NewHTTPError(err, http.StatusNotFound)
}
19 changes: 19 additions & 0 deletions internal/pkg/httperror/model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package httperror

// HTTPError ... errorcode model
type HTTPError struct {
error
Code int
}

func (m *HTTPError) Error() string {
return m.error.Error()
}

// NewHTTPError ... get model
func NewHTTPError(err error, code int) *HTTPError {
return &HTTPError{
error: err,
Code: code,
}
}
Loading

0 comments on commit 07d002c

Please sign in to comment.