Skip to content

Commit

Permalink
refactor(middleware): move middlewares to middleware file (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
vit0rr authored Oct 22, 2024
1 parent 0d86c77 commit ba8dfc6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 46 deletions.
45 changes: 44 additions & 1 deletion api/router/middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package router

import "net/http"
import (
"net/http"
"os"

"github.com/joho/godotenv"
"github.com/vit0rr/short-spot/pkg/log"
)

// SetResponseTypeToJSON is a middleware sets the response type to JSON
func SetResponseTypeToJSON(next http.Handler) http.Handler {
Expand All @@ -9,3 +15,40 @@ func SetResponseTypeToJSON(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}

// AuthMiddleware is a middleware that checks if the request has a valid auth token
func AuthMiddleware(next http.Handler) http.Handler {
godotenv.Load()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
next.ServeHTTP(w, r)
return
}

token := r.Header.Get("Authorization")
if token != os.Getenv("AUTH_TOKEN") {
log.Error(r.Context(), "Unauthorized. Please provide a valid auth token")
http.Error(w, "Unauthorized. Please provide a valid auth token", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
})
}

// CorsMiddleware is a middleware that sets the CORS headers
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")

if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}

next.ServeHTTP(w, r)
})
}
50 changes: 5 additions & 45 deletions api/router/router.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
package router

import (
"net/http"
"os"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
urlshort "github.com/vit0rr/short-spot/api/internal/url-short"
"github.com/vit0rr/short-spot/pkg/deps"
"github.com/vit0rr/short-spot/pkg/log"
"github.com/vit0rr/short-spot/pkg/telemetry"
"go.mongodb.org/mongo-driver/mongo"
)
Expand All @@ -24,12 +19,12 @@ func (router *Router) BuildRoutes() *chi.Mux {
r.Use(middleware.Recoverer)
r.Use(middleware.RealIP)
r.Use(middleware.StripSlashes)
r.Use(SetResponseTypeToJSON)
r.Use(telemetry.TelemetryMiddleware)

// Custom middleware
r.Use(corsMiddleware)
r.Use(authMiddleware)
// Custom middlewares
r.Use(telemetry.TelemetryMiddleware)
r.Use(SetResponseTypeToJSON)
r.Use(CorsMiddleware)
r.Use(AuthMiddleware)

r.Route("/", func(r chi.Router) {
r.Get("/{id}", telemetry.HandleFuncLogger(router.urlshort.Redirect))
Expand All @@ -48,38 +43,3 @@ func New(deps *deps.Deps, db mongo.Database) *Router {
urlshort: urlshort.NewHTTP(deps, &db),
}
}

func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")

if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}

next.ServeHTTP(w, r)
})
}

func authMiddleware(next http.Handler) http.Handler {
godotenv.Load()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
next.ServeHTTP(w, r)
return
}

token := r.Header.Get("Authorization")
if token != os.Getenv("AUTH_TOKEN") {
log.Error(r.Context(), "Unauthorized. Please provide a valid auth token")
http.Error(w, "Unauthorized. Please provide a valid auth token", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
})
}

0 comments on commit ba8dfc6

Please sign in to comment.