Skip to content

Commit

Permalink
imp #12: logger changes to suger and middlewear
Browse files Browse the repository at this point in the history
This adds a middlewear and uses the sugar logger
which will make logger much nicer and allow flippinig
from json/text
  • Loading branch information
donkeyx committed Sep 2, 2023
1 parent 3db15e8 commit e5beda4
Show file tree
Hide file tree
Showing 7 changed files with 200 additions and 92 deletions.
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}"
}
]
}
33 changes: 17 additions & 16 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
module cu-api

go 1.20
go 1.21

require (
github.com/gin-contrib/zap v0.1.0
github.com/gin-gonic/gin v1.9.1
go.uber.org/zap v1.25.0
)

require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/bytedance/sonic v1.10.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-contrib/zap v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/go-playground/validator/v10 v10.15.3 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
go.opentelemetry.io/otel v1.10.0 // indirect
go.opentelemetry.io/otel/trace v1.10.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
go.opentelemetry.io/otel v1.17.0 // indirect
go.opentelemetry.io/otel/trace v1.17.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.4.0 // indirect
golang.org/x/crypto v0.12.0 // indirect
golang.org/x/net v0.14.0 // indirect
golang.org/x/sys v0.11.0 // indirect
golang.org/x/text v0.12.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
79 changes: 47 additions & 32 deletions go.sum

Large diffs are not rendered by default.

87 changes: 59 additions & 28 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,15 @@ package main

import (
"encoding/json"
"net"
"net/http"
"os"
"strings"

"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

func authMiddleware(c *gin.Context) {
authHeader := c.GetHeader("Authorization")

if authHeader != "Bearer "+securityToken {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}

c.Next()
}

func getEnvironmentVariables() map[string]string {
envVariables := make(map[string]string)
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
if len(pair) == 2 {
envVariables[pair[0]] = pair[1]
}
}
return envVariables
}

func envHandler(c *gin.Context) {
envVariables := getEnvironmentVariables()
c.JSON(http.StatusOK, envVariables)
}

func helloHandler(c *gin.Context) {
c.String(http.StatusOK, "Hello, World!")
}
Expand Down Expand Up @@ -72,3 +46,60 @@ func headersHandler(c *gin.Context) {

c.Data(http.StatusOK, "application/json", headersJSON)
}

// functions for the routers
func authMiddleware(c *gin.Context) {
authHeader := c.GetHeader("Authorization")

if authHeader != "Bearer "+securityToken {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}

c.Next()
}

func getEnvironmentVariables() map[string]string {
envVariables := make(map[string]string)
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
if len(pair) == 2 {
envVariables[pair[0]] = pair[1]
}
}
return envVariables
}

// getClientIP extracts the client's IP address from the request.
func getClientIP(r *http.Request) string {
xForwardedFor := r.Header.Get("X-Forwarded-For")
if xForwardedFor != "" {
return xForwardedFor
}

if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return ip
}

return ""
}

func debugHandler(c *gin.Context) {
logger, _ := c.Get("logger")
sugarLogger, _ := logger.(*zap.SugaredLogger)

hostname, _ := os.Hostname()
sourceIP := getClientIP(c.Request)
headers := c.Request.Header

sugarLogger.Infow("Debug Information",
"Hostname", hostname,
"SourceIP", sourceIP,
"UserAgent", headers.Get("User-Agent"),
"Headers", headers,
"RequestURI", c.Request.RequestURI,
)

c.JSON(http.StatusOK, gin.H{"message": "Debug information logged"})
}
47 changes: 35 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package main

import (
"fmt"
"log"
"math/rand"
"sync"
"time"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand All @@ -19,17 +19,15 @@ var (

func main() {

rand.Seed(time.Now().UnixNano())
securityToken = generateRandomToken(32)

// Initialize the logger with JSON output
config := zap.NewProductionConfig()
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, _ := config.Build()
defer logger.Sync()
logger, err := newSugarLogger(false)
if err != nil {
log.Fatal("Error creating logger:", err)
}

logger.Info("Random Security Token", zap.String("token", securityToken))
logCurlCommand(logger)
logger.Info("Curl Command", zap.String("command", getCurlCommand(8080, securityToken)))

isReady = true

Expand All @@ -46,8 +44,33 @@ func generateRandomToken(length int) string {
return string(token)
}

func logCurlCommand(logger *zap.Logger) {
// Log the curl command for the /env endpoint
curlCommand := fmt.Sprintf("curl -H 'Authorization: Bearer %s' http://localhost:8080/env", securityToken)
logger.Info("Curl Command", zap.String("command", curlCommand))
func getCurlCommand(port int, securityToken string) string {
variable := fmt.Sprintf("curl -H 'Authorization: Bearer %s' http://localhost:8080/env", securityToken)
return variable
}

func newSugarLogger(useJSON bool) (*zap.SugaredLogger, error) {
var config zap.Config

if useJSON {
config = zap.NewProductionConfig()
} else {
config = zap.NewDevelopmentConfig()
}

config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

// Configure the logger to write logs to the terminal
config.OutputPaths = []string{"stdout"}

// Create the logger
logger, err := config.Build()
if err != nil {
return nil, err
}

// Create a sugar logger from the base logger
sugarLogger := logger.Sugar()

return sugarLogger, nil
}
22 changes: 22 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

func loggingMiddleware(logger *zap.SugaredLogger) gin.HandlerFunc {
return func(c *gin.Context) {
// Log the request using the sugar logger
logger.Infow("Request Information",
"Method", c.Request.Method,
"Path", c.Request.URL.Path,
"Query", c.Request.URL.RawQuery,
"UserAgent", c.Request.UserAgent(),
)
c.Set("logger", logger)

// Continue handling the request
c.Next()
}
}
9 changes: 5 additions & 4 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ package main

import (
"net/http"
"time"

ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

func setupRouter(logger *zap.Logger) *gin.Engine {
func setupRouter(logger *zap.SugaredLogger) *gin.Engine {

gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.Use(ginzap.Ginzap(logger, time.RFC3339, true))

r.Use(loggingMiddleware(logger))

r.GET("/", helloHandler)
r.GET("/health", healthHandler)
Expand All @@ -25,6 +25,7 @@ func setupRouter(logger *zap.Logger) *gin.Engine {
envVariables := getEnvironmentVariables()
c.JSON(http.StatusOK, envVariables)
})
r.GET("/debug", debugHandler)

return r
}

0 comments on commit e5beda4

Please sign in to comment.