Write a Custom Middleware
January ships with built-in middleware package, which is initialised in the init.january.go
file.
Adding a middleware to your application is 2 simple steps:
- Write the Middleware
- Wire it to the January Router
For this tutorial let’s write a simple CORS
middle.
1. Writing a Middleware
Create a file named cors.go
in the middleware
package and add a method called Cors with a receiver m *Middleware
func (m *Middleware) Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
})
}
now, let’s add the middleware logic to our cors middleware:
func (m *Middleware) Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token, X-Requested-With")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Max-Age", "86400")
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// Call the next handler
next.ServeHTTP(w, r)
})
}
2. Wiring to the January Router
In the init.january.go
file, add the middle just below the apply middleware
comment:
func initApplication() *application {
jan.AppName = "github.com/akshanshgusain/my_crud_srv"
mid := &middleware.Middleware{
App: jan,
}
// ...
// apply middlewares
app.App.Routes.Use(mid.Cors)
// ...
return app
}
Try it out
Run the application with make start
> make start
Building January...
January built!
Starting January...
January started!
~/Downloads/my_crud_srv INFO 2025/05/18 16:41:54 load session called ok | base py
INFO 2025/05/18 16:41:54 Starting January server at http://127.0.0.1:9095/
INFO 2025/05/18 16:41:54 Quit the server with control+c
with your application running, you can test the middleware:
curl -X OPTIONS -i http://localhost:9095 -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST"