Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add location service endpoint #6

Merged
merged 6 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions app/application/location_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package application

import (
"github.com/link-identity/app/domain"
"sync"
)

type ILocation interface {

Check failure on line 8 in app/application/location_service.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type ILocation should have comment or be unexported (revive)

Check failure on line 8 in app/application/location_service.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type ILocation should have comment or be unexported (revive)
GetLastNLocation(rider string, lastN int) []domain.Location
UpdateLocation(rider string, currLocation domain.Location)
}

type location struct {
riderLocations map[string][]domain.Location
sync sync.RWMutex
}

func NewLocationService() ILocation {

Check failure on line 18 in app/application/location_service.go

View workflow job for this annotation

GitHub Actions / build

exported: exported function NewLocationService should have comment or be unexported (revive)

Check failure on line 18 in app/application/location_service.go

View workflow job for this annotation

GitHub Actions / build

exported: exported function NewLocationService should have comment or be unexported (revive)
return &location{}
}

func (l *location) GetLastNLocation(rider string, lastN int) []domain.Location {
//slice := l.riderLocations[riderLocations][len()]
//addr val addr
var locations []domain.Location
for i := len(l.riderLocations[rider]) - 1; i >= len(l.riderLocations[rider])-lastN && i >= 0; i-- {
locations = append(locations, l.riderLocations[rider][i])
}
return locations
}

func (l *location) UpdateLocation(rider string, currLocation domain.Location) {
if l.riderLocations == nil {
l.riderLocations = make(map[string][]domain.Location)
}
if l.riderLocations[rider] == nil {
l.riderLocations[rider] = make([]domain.Location, 0)
}
l.sync.Lock()
defer func() {
l.sync.Unlock()
}()

//err
l.riderLocations[rider] = append(l.riderLocations[rider], currLocation)
}
10 changes: 10 additions & 0 deletions app/domain/location.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package domain

type Location struct {

Check failure on line 3 in app/domain/location.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type Location should have comment or be unexported (revive)

Check failure on line 3 in app/domain/location.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type Location should have comment or be unexported (revive)
Lat float64 `json:"lat"`
Long float64 `json:"long"`
}

//[14, 15, 16] - Lat
//[16, 17, 18] - Long
// 0 , 1, 2
58 changes: 58 additions & 0 deletions app/http/location_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package http

import (
"encoding/json"
"github.com/go-chi/chi"
"github.com/link-identity/app/application"
"github.com/link-identity/app/domain"
"github.com/link-identity/app/utils"
"net/http"
"strconv"
)

type LocationHandler struct {

Check failure on line 13 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type LocationHandler should have comment or be unexported (revive)

Check failure on line 13 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported type LocationHandler should have comment or be unexported (revive)
locationService application.ILocation
}

func NewLocationHandler(locationService application.ILocation) *LocationHandler {

Check failure on line 17 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported function NewLocationHandler should have comment or be unexported (revive)

Check failure on line 17 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported function NewLocationHandler should have comment or be unexported (revive)
return &LocationHandler{
locationService: locationService,
}
}

func (h *LocationHandler) GetLastNLocation(w http.ResponseWriter, r *http.Request) {

Check failure on line 23 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported method LocationHandler.GetLastNLocation should have comment or be unexported (revive)

Check failure on line 23 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported method LocationHandler.GetLastNLocation should have comment or be unexported (revive)
lastN := r.URL.Query().Get("max")
intLastN, ok := strconv.Atoi(lastN)
if ok != nil || intLastN == 0 {
intLastN = 5
}
rider := chi.URLParam(r, "rider")
locations := h.locationService.GetLastNLocation(rider, intLastN)
resp := utils.ResponseDTO{
StatusCode: http.StatusOK,
Data: locations,
}
utils.ResponseJSON(w, http.StatusOK, resp)
}

func (h *LocationHandler) UpdateLocation(w http.ResponseWriter, r *http.Request) {

Check failure on line 38 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported method LocationHandler.UpdateLocation should have comment or be unexported (revive)

Check failure on line 38 in app/http/location_handler.go

View workflow job for this annotation

GitHub Actions / build

exported: exported method LocationHandler.UpdateLocation should have comment or be unexported (revive)
//'{
//"lat": 12.34,
//"long": 56.78
//}'
//'localhost:8080/location/steve/now'
rider := chi.URLParam(r, "rider")

var location domain.Location
if err := json.NewDecoder(r.Body).Decode(&location); err != nil {
resp := utils.NewErrorResponse(http.StatusBadRequest, err.Error())
utils.ResponseJSON(w, http.StatusBadRequest, resp)
return
}
h.locationService.UpdateLocation(rider, location)
resp := utils.ResponseDTO{
StatusCode: http.StatusOK,
Data: nil,
}
utils.ResponseJSON(w, http.StatusOK, resp)
}
65 changes: 36 additions & 29 deletions app/infrastructure/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,51 @@ import (
"errors"
"fmt"
"html/template"
"io"
"net"
"net/http"
"sync"
"time"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/sirupsen/logrus"
)

// logMu is a mutex to control changes on watson.LogData
var logMu sync.RWMutex

// NewLogger create a new logger instance
func NewLogger(logLevel string) *zap.Logger {
ll, err := zap.ParseAtomicLevel(logLevel)
func NewLogger(out io.Writer, logLevel string, env string) *logrus.Logger {
log := logrus.New()
log.Out = out
log.Formatter = getJSONFormatter(env)
level, err := logrus.ParseLevel(logLevel)
if err != nil {
ll = zap.NewAtomicLevelAt(zap.DebugLevel)
level = logrus.DebugLevel
}
config := zap.NewProductionConfig()
config.Level = ll
config.EncoderConfig = getEncoderConfig()
return zap.Must(config.Build())
log.Level = level

return log
}

// getEncoderConfig
func getEncoderConfig() zapcore.EncoderConfig {
encoderCfg := zap.NewProductionEncoderConfig()
encoderCfg.TimeKey = "timestamp"
encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
return encoderCfg
// JSONFormatter Wrapper for logrus.JSONFormatter
type JSONFormatter struct {
logrus.JSONFormatter
}

// getJSONFormatter
func getJSONFormatter(env string) *JSONFormatter {
jsonFormatter := logrus.JSONFormatter{
TimestampFormat: "2006-01-02T15:04:05-0700",
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "@timestamp",
},
PrettyPrint: env == "dev",
}
return &JSONFormatter{jsonFormatter}
}

type loggerMiddleware struct {
logger *zap.Logger
logger *logrus.Entry
}

// Middleware specify a interface to http calls
Expand All @@ -48,7 +59,7 @@ type Middleware interface {
}

// NewLoggerMiddleware ...
func NewLoggerMiddleware(logEntry *zap.Logger) Middleware {
func NewLoggerMiddleware(logEntry *logrus.Entry) Middleware {
return &loggerMiddleware{
logger: logEntry,
}
Expand All @@ -69,37 +80,33 @@ func (lmw *loggerMiddleware) Wrap(next http.Handler) http.Handler {
// copy log data
ld := LogData(r.Context())
ld["status_code"] = lr.StatusCode
ld["response_time"] = fmt.Sprintf("%fms", float64(elapsed)/float64(time.Millisecond))
ld["response_time"] = elapsed.Milliseconds()
ld["request_path"] = r.RequestURI
ld["remote_addr"] = r.RemoteAddr

var logLevel zapcore.Level
var logAttr []zapcore.Field
var logLevel logrus.Level
switch statusCode := lr.StatusCode; {
case statusCode >= http.StatusInternalServerError:
logLevel = zap.ErrorLevel
logLevel = logrus.ErrorLevel
case statusCode >= http.StatusMultipleChoices && statusCode < http.StatusInternalServerError:
logLevel = zap.WarnLevel
logLevel = logrus.WarnLevel
default:
logLevel = zap.InfoLevel
}
for key, value := range ld {
logAttr = append(logAttr, zap.Any(key, value))
logLevel = logrus.InfoLevel
}
lmw.logger.With(logAttr...).Log(logLevel, fmt.Sprintf("[%s]", r.Method))
lmw.logger.WithFields(ld).Logf(logLevel, fmt.Sprintf("[%s] %s", r.Method, r.RequestURI))
}

return http.HandlerFunc(fn)
}

// CoreLogger ...
type CoreLogger struct {
logger *zap.Logger
logger *logrus.Entry
}

// Printf ...
func (c *CoreLogger) Printf(format string, v ...interface{}) {
c.logger.Sugar().Infof(format, v...)
c.logger.Infof(format, v...)
}

// Logger is the interface used internally to log
Expand Down
56 changes: 33 additions & 23 deletions cmd/link-identity-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,43 +19,44 @@ import (
"github.com/link-identity/app/utils"

"github.com/go-chi/chi"
"go.uber.org/zap"
"github.com/sirupsen/logrus"
)

var (
// zap logger instance
logEntryZap *zap.Logger
logEntry *logrus.Entry
)

func init() {
logger := infrastructure.NewLogger(os.Stdout, "info", "test")
hostname, _ := os.Hostname()

logZap := infrastructure.NewLogger("debug")

logEntryZap = logZap.With(
zap.String("env", "dev"),
zap.String("pod_id", hostname),
zap.String("program", "link-identity"),
zap.String("channel", "http"),
)
logEntry = logger.WithFields(logrus.Fields{
"env": "test",
"pod_id": hostname,
"program": "test-app",
"channel": "http",
"request_path": "",
"remote_addr": "",
"status_code": "",
})
}

func main() {
// logger defers
defer logEntryZap.Sync()

// setup database connection
db := sql.NewDBConnection()

repo := repository.NewContactRepository(db)

service := application.NewService(repo)
handler := httpHandler.NewLinkIdentityHandler(service)
identityService := application.NewService(repo)
identityHandler := httpHandler.NewLinkIdentityHandler(identityService)

locationService := application.NewLocationService()
locationHandler := httpHandler.NewLocationHandler(locationService)

// setup the http server
router := SetupRouters(handler)
router := SetupRouters(identityHandler, locationHandler)

// service address will be changed as port in next PR.
// identityService address will be changed as port in next PR.
srv := &http.Server{
Addr: fmt.Sprintf(":%s", appconfig.Values.Server.Port),
ReadTimeout: 10 * time.Second,
Expand Down Expand Up @@ -87,29 +88,38 @@ func main() {
serverStopCtx()
}()
// Run the server
logEntryZap.Info("Starting application at port: " + appconfig.Values.Server.Port)
logEntry.Info("Starting application at port: " + appconfig.Values.Server.Port)
errServer := srv.ListenAndServe()
if errServer != nil && errServer != http.ErrServerClosed {
log.Fatal(errServer)
}
// Wait for server context to be stopped
<-serverCtx.Done()
logEntryZap.Info("Application stopped gracefully!")
logEntry.Info("Application stopped gracefully!")
}

// SetupRouters ...
func SetupRouters(handler *httpHandler.LinkIdentityHandler) *chi.Mux {
func SetupRouters(identityHandler *httpHandler.LinkIdentityHandler, locationHandler *httpHandler.LocationHandler) *chi.Mux {
// Base route initialize.
router := chi.NewRouter()
router.Use(infrastructure.NewLoggerMiddleware(logEntryZap).Wrap)
router.Use(infrastructure.NewLoggerMiddleware(logEntry).Wrap)

//Health check registration
router.Get("/health/check", GetHealthCheck)
router.Get("/", GetHealthCheck)

// Register Contact get handler
{
router.Post("/identify", handler.Identify)
router.Post("/identify", identityHandler.Identify)
}

// location handler
{
//'localhost:8080/location/
//steve?max=3
router.Get("/location/{rider}", locationHandler.GetLastNLocation)
//'localhost:8080/location/steve/now'
router.Post("/location/{rider}/now", locationHandler.UpdateLocation)
}
return router
}
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ require (
github.com/joho/godotenv v1.5.1
github.com/nyaruka/phonenumbers v1.3.4
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
go.uber.org/zap v1.27.0
gorm.io/driver/postgres v1.5.7
gorm.io/gorm v1.25.9
)
Expand All @@ -24,8 +24,8 @@ require (
github.com/kr/pretty v0.3.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/stretchr/objx v0.5.2 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/crypto v0.16.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
11 changes: 5 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,20 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
Expand Down
Loading