package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
gohooks "github.com/odigos-io/odigos/hooks/go/gin"
)
func main() {
r := gin.New()
// Define all individual middleware
middlewares := []gin.HandlerFunc{
LoggerMiddleware(),
AuthMiddleware(),
}
// Use the wrapper that chains the middleware
r.Use(gohooks.OdigosGinMiddleware(middlewares...)...)
// Sample route
r.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, world!"})
})
r.Run(":8080")
}
// LoggerMiddleware logs the request method, path, and duration.
func LoggerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
log.Printf("Request: %s %s | Duration: %v", c.Request.Method, c.Request.URL.Path, time.Since(start))
}
}
// AuthMiddleware checks for a static bearer token in the Authorization header.
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "Bearer secret-token" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}