Skip to content

Commit

Permalink
ref: change log format
Browse files Browse the repository at this point in the history
  • Loading branch information
kenriortega committed Nov 11, 2021
1 parent 08a63e4 commit 95f454b
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 33 deletions.
4 changes: 2 additions & 2 deletions internal/proxy/domain/lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (s *ServerPool) HealthCheck() {
if !alive {
status = "down"
}
logger.LogInfo(fmt.Sprintf("%s [%s]\n", b.URL, status))
logger.LogInfo(fmt.Sprintf("lb: %s [%s]\n", b.URL, status))
}
}

Expand All @@ -105,7 +105,7 @@ func isBackendAlive(u *url.URL) bool {
timeout := 2 * time.Second
conn, err := net.DialTimeout("tcp", u.Host, timeout)
if err != nil {
logger.LogError(errors.ErrIsBackendAlive.Error())
logger.LogError(errors.Errorf("lb: %v", errors.ErrIsBackendAlive).Error())
return false
}
_ = conn.Close()
Expand Down
36 changes: 17 additions & 19 deletions internal/proxy/domain/proxyrepository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package proxy

import (
"context"
"fmt"
"os"

badger "github.com/dgraph-io/badger/v3"
"github.com/go-redis/redis/v8"
Expand Down Expand Up @@ -41,39 +39,39 @@ func (r ProxyRepositoryStorage) SaveKEY(engine, key, apikey string) error {
logger.LogError(errors.ErrSavekeyUpdateTX.Error())
return errors.ErrSavekeyUpdateTX
}
logger.LogInfo("savekey: successful")
logger.LogInfo("proxy: savekey was successful")

return nil
}); err != nil {
logger.LogError(errors.ErrSavekeyUpdate.Error())

return errors.ErrSavekeyUpdate
}

return nil
case "redis":
if _, err := r.clientRdb.HSet(context.TODO(), key, apikey).Result(); err != nil {
logger.LogError(err.Error())
logger.LogError(errors.Errorf("proxy redis: %v", err).Error())
}
// r.clientRdb.Expire(context.TODO(), key, 24*time.Hour)
case "local":
f, err := os.Create("./apikey")
// case "local":
// f, err := os.Create("./apikey")

if err != nil {
logger.LogError(errors.ErrSavekeyCreateLocal.Error())
return errors.ErrSavekeyCreateLocal
}
// if err != nil {
// logger.LogError(errors.ErrSavekeyCreateLocal.Error())
// return errors.ErrSavekeyCreateLocal
// }

// defer f.Close()
// // defer f.Close()

data := []byte(fmt.Sprintf("%s:%s", key, apikey))
// data := []byte(fmt.Sprintf("%s:%s", key, apikey))

_, err = f.Write(data)
// _, err = f.Write(data)

if err != nil {
logger.LogError(errors.ErrSavekeyWriteOnLocal.Error())
return errors.ErrSavekeyWriteOnLocal
}
return nil
// if err != nil {
// logger.LogError(errors.ErrSavekeyWriteOnLocal.Error())
// return errors.ErrSavekeyWriteOnLocal
// }
// return nil
}
return nil
}
Expand Down
5 changes: 2 additions & 3 deletions internal/proxy/handlers/lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func GetRetryFromContext(r *http.Request) int {
func Lbalancer(w http.ResponseWriter, r *http.Request) {
attempts := GetAttemptsFromContext(r)
if attempts > 3 {
logger.LogInfo(fmt.Sprintf("%s(%s) Max attempts reached, terminating\n", r.RemoteAddr, r.URL.Path))
logger.LogInfo(fmt.Sprintf("lb: %s(%s) Max attempts reached, terminating\n", r.RemoteAddr, r.URL.Path))
http.Error(w, errors.ErrLBHttp.Error(), http.StatusServiceUnavailable)
return
}
Expand All @@ -50,8 +50,7 @@ func Lbalancer(w http.ResponseWriter, r *http.Request) {
func HealthCheck() {
t := time.NewTicker(time.Minute * 1)
for range t.C {
logger.LogInfo("Starting health check...")
ServerPool.HealthCheck()
logger.LogInfo("Health check completed")
logger.LogInfo("lb: Health check completed")
}
}
25 changes: 16 additions & 9 deletions internal/proxy/handlers/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ type ProxyHandler struct {
func (ph *ProxyHandler) SaveSecretKEY(engine, key, apikey string) {
result, err := ph.Service.SaveSecretKEY(engine, key, apikey)
if err != nil {
logger.LogInfo(result)
logger.LogError(errors.Errorf("proxy: SaveSecretKEY %v", err).Error())
}
logger.LogInfo(result)
logger.LogInfo("proxy: SaveSecretKEY" + result)
}

// ProxyGateway handler for management all request
Expand All @@ -54,7 +54,8 @@ func (ph *ProxyHandler) ProxyGateway(endpoints domain.ProxyEndpoint, engine, key
fmt.Sprintf("%s%s", endpoints.HostURI, endpoint.PathEndpoint),
)
if err != nil {
logger.LogError(err.Error())
logger.LogError(errors.Errorf("proxy: %v", err).Error())

}
if endpoint.PathProtected {
proxy = httputil.NewSingleHostReverseProxy(target)
Expand Down Expand Up @@ -130,21 +131,26 @@ func checkJWTSecretKeyFromRequest(req *http.Request, key string) error {
hs := jwt.NewHS256([]byte(key))
now := time.Now()
if !strings.HasPrefix(header, "Bearer ") {
logger.LogError(errors.ErrBearerTokenFormat.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrBearerTokenFormat).Error())

return errors.ErrBearerTokenFormat
}

token := strings.Split(header, " ")[1]
pl := JWTPayload{}
expValidator := jwt.ExpirationTimeValidator(now)
validatePayload := jwt.ValidatePayload(&pl.Payload, expValidator)

_, err := jwt.Verify([]byte(token), hs, &pl, validatePayload)

if errors.ErrorIs(err, jwt.ErrExpValidation) {
logger.LogError(errors.ErrTokenExpValidation.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrTokenExpValidation).Error())

return errors.ErrTokenExpValidation
}
if errors.ErrorIs(err, jwt.ErrHMACVerification) {
logger.LogError(errors.ErrTokenHMACValidation.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrTokenHMACValidation).Error())

return errors.ErrTokenHMACValidation
}

Expand All @@ -156,13 +162,14 @@ func checkAPIKEYSecretKeyFromRequest(req *http.Request, ph *ProxyHandler, engine
apikey, err := ph.Service.GetKEY(engine, key)
header := req.Header.Get("X-API-KEY") // pass to constants
if err != nil {
logger.LogError(errors.ErrGetkeyView.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrGetkeyView).Error())

}
if apikey == header {
logger.LogInfo("OK")
logger.LogInfo("proxy: check secret from request OK")
return nil
} else {
logger.LogInfo("Invalid apikey")
logger.LogError(errors.Errorf("proxy: Invalid API KEY").Error())
return errors.NewError("Invalid API KEY")
}
}
Expand Down

0 comments on commit 95f454b

Please sign in to comment.