Skip to content

Commit c54742f

Browse files
committed
feat: add log middleware
1 parent b7c935c commit c54742f

File tree

4 files changed

+31
-11
lines changed

4 files changed

+31
-11
lines changed

app/middlewares/log.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package middlewares
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"time"
7+
8+
"github.com/sirupsen/logrus"
9+
)
10+
11+
func (m *Middleware) LogMiddleware(next http.Handler) http.Handler {
12+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13+
fmt.Println("hiteed")
14+
start := time.Now()
15+
16+
// Call the next handler
17+
next.ServeHTTP(w, r)
18+
19+
// Log request details with Logrus
20+
logrus.WithFields(logrus.Fields{
21+
"method": r.Method,
22+
"url": r.URL.Path,
23+
"duration": time.Since(start).String(),
24+
}).Info("Request processed")
25+
})
26+
}

cmd/serve_http.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ import (
1616
"github.com/hammer-code/lms-be/domain"
1717
"github.com/hammer-code/lms-be/utils"
1818
"github.com/sirupsen/logrus"
19-
"github.com/swaggo/http-swagger"
19+
httpSwagger "github.com/swaggo/http-swagger"
20+
2021
// _ "swagger-mux/docs"
2122
"github.com/rs/cors"
2223
"github.com/spf13/cobra"
@@ -37,14 +38,10 @@ var serveHttpCmd = &cobra.Command{
3738

3839
// route
3940
router := registerHandler(app)
40-
// router.Use(cors.Default().Handler)
41+
router.Use(app.Middleware.LogMiddleware)
4142

4243
// build cors
43-
muxCorsWithRouter := cors.New(cors.Options{
44-
AllowedOrigins: []string{"*", "http://localhost:8000"},
45-
AllowedMethods: []string{"*"},
46-
AllowedHeaders: []string{"*"},
47-
}).Handler(router)
44+
muxCorsWithRouter := cors.AllowAll().Handler(router)
4845

4946
srv := &http.Server{
5047
Addr: cfg.APP_PORT,

config/config.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,6 @@ func GetConfig() Config {
6666
methods = strings.Split(corsMethods, ",")
6767
}
6868

69-
logrus.Info("cors_allow_origins :", origins)
70-
logrus.Info("cors_allow_headers :", headers)
71-
logrus.Info("cors_allow_methods :", methods)
72-
7369
c = &Config{
7470
APP_ENV: viper.GetString("APP_ENV"),
7571
APP_NAME: viper.GetString("APP_NAME"),

domain/middleware.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ import "net/http"
44

55
type Middleware interface {
66
AuthMiddleware(next http.Handler) http.Handler
7+
LogMiddleware(next http.Handler) http.Handler
78
}

0 commit comments

Comments
 (0)