Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d0ab3c0f2 | |||
| ec4a0ac231 | |||
| 5885b42816 | |||
| 216fe93a55 | |||
| 855b82e9df | |||
| f91090b35e | |||
| 5b380a294b | |||
| ddb4b35181 | |||
| f8cdf3a511 | |||
| e6a8880fd3 | |||
| aa6ba87f4e |
234
README.md
234
README.md
@@ -1,115 +1,153 @@
|
|||||||
# Mux
|
# Mux - A Lightweight HTTP Router for Go
|
||||||
|
|
||||||
Tiny wrapper around Go's builtin http.ServeMux with easy routing methods.
|
Mux is a simple, lightweight HTTP router for Go that wraps around the standard `http.ServeMux` to provide additional functionality and a more ergonomic API.
|
||||||
|
|
||||||
## Example
|
## Features
|
||||||
|
|
||||||
|
- HTTP method-specific routing (GET, POST, PUT, DELETE, etc.)
|
||||||
|
- Middleware support with flexible stacking
|
||||||
|
- Route grouping for organization and shared middleware
|
||||||
|
- RESTful resource routing
|
||||||
|
- URL parameter extraction
|
||||||
|
- Graceful shutdown support
|
||||||
|
- Minimal dependencies (only uses Go standard library)
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go get code.patial.tech/go/mux
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log/slog"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"gitserver.in/patialtech/mux"
|
"code.patial.tech/go/mux"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// create a new router
|
// Create a new router
|
||||||
r := mux.NewRouter()
|
router := mux.NewRouter()
|
||||||
|
|
||||||
// you can use any middleware that is: "func(http.Handler) http.Handler"
|
// Define a simple route
|
||||||
// so you can use any of it
|
router.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
// - https://github.com/gorilla/handlers
|
fmt.Fprint(w, "Hello, World!")
|
||||||
// - https://github.com/go-chi/chi/tree/master/middleware
|
|
||||||
|
|
||||||
// add some root level middlewares, these will apply to all routes after it
|
|
||||||
r.Use(middleware1, middleware2)
|
|
||||||
|
|
||||||
// let's add a route
|
|
||||||
r.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("i am route /hello"))
|
|
||||||
})
|
|
||||||
// r.Post(pattern string, h http.HandlerFunc)
|
|
||||||
// r.Put(pattern string, h http.HandlerFunc)
|
|
||||||
// ...
|
|
||||||
|
|
||||||
// you can inline middleware(s) to a route
|
|
||||||
r.
|
|
||||||
With(mwInline).
|
|
||||||
GET("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("i am route /hello-2 with my own middleware"))
|
|
||||||
})
|
|
||||||
|
|
||||||
// define a resource
|
|
||||||
r.Resource("/photos", func(resource *mux.Resource) {
|
|
||||||
// rails style resource routes
|
|
||||||
// GET /photos
|
|
||||||
// GET /photos/new
|
|
||||||
// POST /photos
|
|
||||||
// GET /photos/:id
|
|
||||||
// GET /photos/:id/edit
|
|
||||||
// PUT /photos/:id
|
|
||||||
// PATCH /photos/:id
|
|
||||||
// DELETE /photos/:id
|
|
||||||
resource.Index(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("all photos"))
|
|
||||||
})
|
|
||||||
|
|
||||||
resource.New(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("upload a new pohoto"))
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// create a group of few routes with their own middlewares
|
// Start the server
|
||||||
r.Group(func(grp *mux.Router) {
|
http.ListenAndServe(":8080", router)
|
||||||
grp.Use(mwGroup)
|
|
||||||
grp.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("i am route /group"))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
// catches all
|
|
||||||
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("hello there"))
|
|
||||||
})
|
|
||||||
|
|
||||||
// Serve allows graceful shutdown, you can use it
|
|
||||||
r.Serve(func(srv *http.Server) error {
|
|
||||||
srv.Addr = ":3001"
|
|
||||||
// srv.ReadTimeout = time.Minute
|
|
||||||
// srv.WriteTimeout = time.Minute
|
|
||||||
|
|
||||||
slog.Info("listening on http://localhost" + srv.Addr)
|
|
||||||
return srv.ListenAndServe()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func middleware1(h http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
slog.Info("i am middleware 1")
|
|
||||||
h.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func middleware2(h http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
slog.Info("i am middleware 2")
|
|
||||||
h.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func mwInline(h http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
slog.Info("i am inline middleware")
|
|
||||||
h.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func mwGroup(h http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
slog.Info("i am group middleware")
|
|
||||||
h.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Routing
|
||||||
|
|
||||||
|
Mux supports all HTTP methods defined in the Go standard library:
|
||||||
|
|
||||||
|
```go
|
||||||
|
router.GET("/users", listUsers)
|
||||||
|
router.POST("/users", createUser)
|
||||||
|
router.PUT("/users/{id}", updateUser)
|
||||||
|
router.DELETE("/users/{id}", deleteUser)
|
||||||
|
router.PATCH("/users/{id}", partialUpdateUser)
|
||||||
|
router.HEAD("/users", headUsers)
|
||||||
|
router.OPTIONS("/users", optionsUsers)
|
||||||
|
router.TRACE("/users", traceUsers)
|
||||||
|
router.CONNECT("/users", connectUsers)
|
||||||
|
```
|
||||||
|
|
||||||
|
## URL Parameters
|
||||||
|
|
||||||
|
Mux supports URL parameters using curly braces:
|
||||||
|
|
||||||
|
```go
|
||||||
|
router.GET("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := r.PathValue("id")
|
||||||
|
fmt.Fprintf(w, "User ID: %s", id)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Middleware
|
||||||
|
|
||||||
|
Middleware functions take an `http.Handler` and return an `http.Handler`. You can add global middleware to all routes:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Logging middleware
|
||||||
|
func loggingMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Printf("[%s] %s\n", r.Method, r.URL.Path)
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add middleware to all routes
|
||||||
|
router.Use(loggingMiddleware)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Route Groups
|
||||||
|
|
||||||
|
Group related routes and apply middleware to specific groups:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// API routes group
|
||||||
|
router.Group(func(api *mux.Router) {
|
||||||
|
// Middleware only for API routes
|
||||||
|
api.Use(authMiddleware)
|
||||||
|
|
||||||
|
// API routes
|
||||||
|
api.GET("/api/users", listUsers)
|
||||||
|
api.POST("/api/users", createUser)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## RESTful Resources
|
||||||
|
|
||||||
|
Easily define RESTful resources:
|
||||||
|
|
||||||
|
```go
|
||||||
|
router.Resource("/posts", func(r *mux.Resource) {
|
||||||
|
r.Index(listPosts) // GET /posts
|
||||||
|
r.Show(showPost) // GET /posts/{id}
|
||||||
|
r.Create(createPost) // POST /posts
|
||||||
|
r.Update(updatePost) // PUT /posts/{id}
|
||||||
|
r.Destroy(deletePost) // DELETE /posts/{id}
|
||||||
|
r.New(newPostForm) // GET /posts/new
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Graceful Shutdown
|
||||||
|
|
||||||
|
Use the built-in graceful shutdown functionality:
|
||||||
|
|
||||||
|
```go
|
||||||
|
router.Serve(func(srv *http.Server) error {
|
||||||
|
srv.Addr = ":8080"
|
||||||
|
return srv.ListenAndServe()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom 404 Handler
|
||||||
|
|
||||||
|
can be tried like this
|
||||||
|
|
||||||
|
```go
|
||||||
|
router.GET("/", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
|
if request.URL.Path != "/" {
|
||||||
|
writer.WriteHeader(404)
|
||||||
|
writer.Write([]byte(`not found, da xiong dei !!!`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Full Example
|
||||||
|
|
||||||
|
See the [examples directory](./example) for complete working examples.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
|
||||||
|
|||||||
@@ -4,16 +4,30 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"gitserver.in/patialtech/mux"
|
"code.patial.tech/go/mux"
|
||||||
"gitserver.in/patialtech/mux/middleware"
|
"code.patial.tech/go/mux/middleware"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// create a new router
|
// create a new router
|
||||||
r := mux.NewRouter()
|
m := mux.New()
|
||||||
r.Use(middleware.CORS(middleware.CORSOption{
|
m.Use(middleware.CORS(middleware.CORSOption{
|
||||||
AllowedOrigins: []string{"*"},
|
AllowedOrigins: []string{"*"},
|
||||||
MaxAge: 60,
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||||
|
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-AccessToken", "X-Real-IP"},
|
||||||
|
ExposedHeaders: []string{"Link"},
|
||||||
|
AllowCredentials: true,
|
||||||
|
MaxAge: 300,
|
||||||
|
}))
|
||||||
|
|
||||||
|
m.Use(middleware.Helmet(middleware.HelmetOption{
|
||||||
|
StrictTransportSecurity: &middleware.TransportSecurity{
|
||||||
|
MaxAge: 31536000,
|
||||||
|
IncludeSubDomains: true,
|
||||||
|
Preload: true,
|
||||||
|
},
|
||||||
|
XssProtection: true,
|
||||||
|
XFrameOption: middleware.XFrameDeny,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// you can use any middleware that is: "func(http.Handler) http.Handler"
|
// you can use any middleware that is: "func(http.Handler) http.Handler"
|
||||||
@@ -22,10 +36,10 @@ func main() {
|
|||||||
// - https://github.com/go-chi/chi/tree/master/middleware
|
// - https://github.com/go-chi/chi/tree/master/middleware
|
||||||
|
|
||||||
// add some root level middlewares, these will apply to all routes after it
|
// add some root level middlewares, these will apply to all routes after it
|
||||||
r.Use(middleware1, middleware2)
|
m.Use(middleware1, middleware2)
|
||||||
|
|
||||||
// let's add a route
|
// let's add a route
|
||||||
r.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
|
m.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("i am route /hello"))
|
w.Write([]byte("i am route /hello"))
|
||||||
})
|
})
|
||||||
// r.Post(pattern string, h http.HandlerFunc)
|
// r.Post(pattern string, h http.HandlerFunc)
|
||||||
@@ -33,34 +47,45 @@ func main() {
|
|||||||
// ...
|
// ...
|
||||||
|
|
||||||
// you can inline middleware(s) to a route
|
// you can inline middleware(s) to a route
|
||||||
r.
|
m.
|
||||||
With(mwInline).
|
With(mwInline).
|
||||||
GET("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
GET("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("i am route /hello-2 with my own middleware"))
|
w.Write([]byte("i am route /hello-2 with my own middleware"))
|
||||||
})
|
})
|
||||||
|
|
||||||
// define a resource
|
// define a resource
|
||||||
r.Resource("/photos", func(resource *mux.Resource) {
|
m.Resource("/photos", func(res *mux.Resource) {
|
||||||
// Rails style resource routes
|
res.Index(func(w http.ResponseWriter, r *http.Request) {
|
||||||
// GET /photos
|
|
||||||
// GET /photos/new
|
|
||||||
// POST /photos
|
|
||||||
// GET /photos/:id
|
|
||||||
// GET /photos/:id/edit
|
|
||||||
// PUT /photos/:id
|
|
||||||
// PATCH /photos/:id
|
|
||||||
// DELETE /photos/:id
|
|
||||||
resource.Index(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("all photos"))
|
w.Write([]byte("all photos"))
|
||||||
})
|
})
|
||||||
|
|
||||||
resource.New(func(w http.ResponseWriter, r *http.Request) {
|
res.CreateView(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("upload a new pohoto"))
|
w.Write([]byte("new photo view"))
|
||||||
|
})
|
||||||
|
|
||||||
|
res.Create(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("new photo"))
|
||||||
|
})
|
||||||
|
|
||||||
|
res.View(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("view photo detail"))
|
||||||
|
})
|
||||||
|
|
||||||
|
res.Update(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("update photos"))
|
||||||
|
})
|
||||||
|
|
||||||
|
res.UpdatePartial(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("update few of photo fields"))
|
||||||
|
})
|
||||||
|
|
||||||
|
res.Delete(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("removed a phot"))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// create a group of few routes with their own middlewares
|
// create a group of few routes with their own middlewares
|
||||||
r.Group(func(grp *mux.Router) {
|
m.Group(func(grp *mux.Mux) {
|
||||||
grp.Use(mwGroup)
|
grp.Use(mwGroup)
|
||||||
grp.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
grp.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("i am route /group"))
|
w.Write([]byte("i am route /group"))
|
||||||
@@ -68,12 +93,16 @@ func main() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// catches all
|
// catches all
|
||||||
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
m.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Write([]byte("hello there"))
|
w.Write([]byte("hello there"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
m.GET("/routes", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
m.PrintRoutes(w)
|
||||||
|
})
|
||||||
|
|
||||||
// Serve allows graceful shutdown, you can use it
|
// Serve allows graceful shutdown, you can use it
|
||||||
r.Serve(func(srv *http.Server) error {
|
m.Serve(func(srv *http.Server) error {
|
||||||
srv.Addr = ":3001"
|
srv.Addr = ":3001"
|
||||||
// srv.ReadTimeout = time.Minute
|
// srv.ReadTimeout = time.Minute
|
||||||
// srv.WriteTimeout = time.Minute
|
// srv.WriteTimeout = time.Minute
|
||||||
|
|||||||
4
go.mod
4
go.mod
@@ -1,3 +1,3 @@
|
|||||||
module gitserver.in/patialtech/mux
|
module code.patial.tech/go/mux
|
||||||
|
|
||||||
go 1.23.2
|
go 1.24
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ type OriginValidator func(string) bool
|
|||||||
var (
|
var (
|
||||||
defaultCorsOptionStatusCode = http.StatusOK
|
defaultCorsOptionStatusCode = http.StatusOK
|
||||||
defaultCorsMethods = []string{http.MethodHead, http.MethodGet, http.MethodPost}
|
defaultCorsMethods = []string{http.MethodHead, http.MethodGet, http.MethodPost}
|
||||||
defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin"}
|
defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
|
||||||
// (WebKit/Safari v9 sends the Origin header by default in AJAX requests).
|
// (WebKit/Safari v9 sends the Origin header by default in AJAX requests).
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
// Author: Ankit Patial
|
||||||
|
// inspired from Helmet.js
|
||||||
|
// https://github.com/helmetjs/helmet/tree/main
|
||||||
|
|
||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -6,9 +10,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// inspired from Helmet.js
|
|
||||||
// https://github.com/helmetjs/helmet/tree/main
|
|
||||||
|
|
||||||
type (
|
type (
|
||||||
HelmetOption struct {
|
HelmetOption struct {
|
||||||
ContentSecurityPolicy CSP
|
ContentSecurityPolicy CSP
|
||||||
@@ -101,20 +102,17 @@ type (
|
|||||||
const (
|
const (
|
||||||
YearDuration = 365 * 24 * 60 * 60
|
YearDuration = 365 * 24 * 60 * 60
|
||||||
|
|
||||||
// EmbedderDefault default value will be "require-corp"
|
// OpenerSameOrigin is default if no value supplied
|
||||||
EmbedderDefault Embedder = ""
|
|
||||||
EmbedderRequireCorp Embedder = "require-corp"
|
|
||||||
EmbedderCredentialLess Embedder = "credentialless"
|
|
||||||
EmbedderUnsafeNone Embedder = "unsafe-none"
|
|
||||||
|
|
||||||
// OpenerDefault default value will be "same-origin"
|
|
||||||
OpenerDefault Opener = ""
|
|
||||||
OpenerSameOrigin Opener = "same-origin"
|
OpenerSameOrigin Opener = "same-origin"
|
||||||
OpenerSameOriginAllowPopups Opener = "same-origin-allow-popups"
|
OpenerSameOriginAllowPopups Opener = "same-origin-allow-popups"
|
||||||
OpenerUnsafeNone Opener = "unsafe-none"
|
OpenerUnsafeNone Opener = "unsafe-none"
|
||||||
|
|
||||||
|
// EmbedderDefault is default if no value supplied
|
||||||
|
EmbedderRequireCorp Embedder = "require-corp"
|
||||||
|
EmbedderCredentialLess Embedder = "credentialless"
|
||||||
|
EmbedderUnsafeNone Embedder = "unsafe-none"
|
||||||
|
|
||||||
// ResourceDefault default value will be "same-origin"
|
// ResourceDefault default value will be "same-origin"
|
||||||
ResourceDefault Resource = ""
|
|
||||||
ResourceSameOrigin Resource = "same-origin"
|
ResourceSameOrigin Resource = "same-origin"
|
||||||
ResourceSameSite Resource = "same-site"
|
ResourceSameSite Resource = "same-site"
|
||||||
ResourceCrossOrigin Resource = "cross-origin"
|
ResourceCrossOrigin Resource = "cross-origin"
|
||||||
@@ -128,15 +126,13 @@ const (
|
|||||||
StrictOriginWhenCrossOrigin Referrer = "strict-origin-when-cross-origin"
|
StrictOriginWhenCrossOrigin Referrer = "strict-origin-when-cross-origin"
|
||||||
UnsafeUrl Referrer = "unsafe-url"
|
UnsafeUrl Referrer = "unsafe-url"
|
||||||
|
|
||||||
// CDPDefault default value is "none"
|
// CDPNone is default if no value supplied
|
||||||
CDPDefault CDP = ""
|
|
||||||
CDPNone CDP = "none"
|
CDPNone CDP = "none"
|
||||||
CDPMasterOnly CDP = "master-only"
|
CDPMasterOnly CDP = "master-only"
|
||||||
CDPByContentType CDP = "by-content-type"
|
CDPByContentType CDP = "by-content-type"
|
||||||
CDPAll CDP = "all"
|
CDPAll CDP = "all"
|
||||||
|
|
||||||
// XFrameDefault default value will be "sameorigin"
|
// XFrameSameOrigin is default if no value supplied
|
||||||
XFrameDefault XFrame = ""
|
|
||||||
XFrameSameOrigin XFrame = "sameorigin"
|
XFrameSameOrigin XFrame = "sameorigin"
|
||||||
XFrameDeny XFrame = "deny"
|
XFrameDeny XFrame = "deny"
|
||||||
)
|
)
|
||||||
@@ -147,22 +143,15 @@ func Helmet(opt HelmetOption) func(http.Handler) http.Handler {
|
|||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Add("Content-Security-Policy", opt.ContentSecurityPolicy.value())
|
w.Header().Add("Content-Security-Policy", opt.ContentSecurityPolicy.value())
|
||||||
|
|
||||||
// Cross-Origin-Embedder-Policy, if nil set default
|
// Opener-Policy
|
||||||
if opt.CrossOriginEmbedderPolicy == EmbedderDefault {
|
if opt.CrossOriginOpenerPolicy == "" {
|
||||||
w.Header().Add("Cross-Origin-Embedder-Policy", string(EmbedderRequireCorp))
|
|
||||||
} else {
|
|
||||||
w.Header().Add("Cross-Origin-Embedder-Policy", string(opt.CrossOriginEmbedderPolicy))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cross-Origin-Opener-Policy, if nil set default
|
|
||||||
if opt.CrossOriginOpenerPolicy == OpenerDefault {
|
|
||||||
w.Header().Add("Cross-Origin-Opener-Policy", string(OpenerSameOrigin))
|
w.Header().Add("Cross-Origin-Opener-Policy", string(OpenerSameOrigin))
|
||||||
} else {
|
} else {
|
||||||
w.Header().Add("Cross-Origin-Opener-Policy", string(opt.CrossOriginOpenerPolicy))
|
w.Header().Add("Cross-Origin-Opener-Policy", string(opt.CrossOriginOpenerPolicy))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cross-Origin-Resource-Policy, if nil set default
|
// Resource-Policy
|
||||||
if opt.CrossOriginResourcePolicy == ResourceDefault {
|
if opt.CrossOriginResourcePolicy == "" {
|
||||||
w.Header().Add("Cross-Origin-Resource-Policy", string(ResourceSameOrigin))
|
w.Header().Add("Cross-Origin-Resource-Policy", string(ResourceSameOrigin))
|
||||||
} else {
|
} else {
|
||||||
w.Header().Add("Cross-Origin-Resource-Policy", string(opt.CrossOriginResourcePolicy))
|
w.Header().Add("Cross-Origin-Resource-Policy", string(opt.CrossOriginResourcePolicy))
|
||||||
@@ -223,13 +212,13 @@ func Helmet(opt HelmetOption) func(http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// indicate whether a browser should be allowed to render a page in iframe | frame | embed | object
|
// indicate whether a browser should be allowed to render a page in iframe | frame | embed | object
|
||||||
if opt.XFrameOption == XFrameDefault {
|
if opt.XFrameOption == "" {
|
||||||
w.Header().Add("X-Frame-Options", string(XFrameSameOrigin))
|
w.Header().Add("X-Frame-Options", string(XFrameSameOrigin))
|
||||||
} else {
|
} else {
|
||||||
w.Header().Add("X-Frame-Options", string(opt.XFrameOption))
|
w.Header().Add("X-Frame-Options", string(opt.XFrameOption))
|
||||||
}
|
}
|
||||||
|
|
||||||
if opt.CrossDomainPolicies == CDPDefault {
|
if opt.CrossDomainPolicies == "" {
|
||||||
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(CDPNone))
|
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(CDPNone))
|
||||||
} else {
|
} else {
|
||||||
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(opt.CrossDomainPolicies))
|
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(opt.CrossDomainPolicies))
|
||||||
@@ -279,7 +268,7 @@ func (csp *CSP) value() string {
|
|||||||
|
|
||||||
sb.WriteString(fmt.Sprintf(
|
sb.WriteString(fmt.Sprintf(
|
||||||
"style-src %s; ",
|
"style-src %s; ",
|
||||||
cspNormalised(csp.StyleSrc, []string{"self", "https:", "unsafe-inline"}),
|
cspNormalised(csp.StyleSrc, []string{"self", "unsafe-inline"}),
|
||||||
))
|
))
|
||||||
|
|
||||||
sb.WriteString(fmt.Sprintf(
|
sb.WriteString(fmt.Sprintf(
|
||||||
@@ -299,7 +288,7 @@ func (csp *CSP) value() string {
|
|||||||
|
|
||||||
sb.WriteString(fmt.Sprintf(
|
sb.WriteString(fmt.Sprintf(
|
||||||
"font-src %s; ",
|
"font-src %s; ",
|
||||||
cspNormalised(csp.FontSrc, []string{"self", "https:", "data:"}),
|
cspNormalised(csp.FontSrc, []string{"self", "data:"}),
|
||||||
))
|
))
|
||||||
|
|
||||||
sb.WriteString(fmt.Sprintf(
|
sb.WriteString(fmt.Sprintf(
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitserver.in/patialtech/mux"
|
"code.patial.tech/go/mux"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestHelmet(t *testing.T) {
|
func TestHelmet(t *testing.T) {
|
||||||
r := mux.NewRouter()
|
r := mux.New()
|
||||||
r.Use(Helmet(HelmetOption{}))
|
r.Use(Helmet(HelmetOption{}))
|
||||||
r.Get("/hello", func(writer http.ResponseWriter, request *http.Request) {
|
r.GET("/hello", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
_, _ = writer.Write([]byte("hello there"))
|
_, _ = writer.Write([]byte("hello there"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
167
mux.go
Normal file
167
mux.go
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Mux is a wrapper around the go's standard http.ServeMux.
|
||||||
|
// It's a lean wrapper with methods to make routing easier
|
||||||
|
type Mux struct {
|
||||||
|
mux *http.ServeMux
|
||||||
|
middlewares []func(http.Handler) http.Handler
|
||||||
|
routes *RouteList
|
||||||
|
IsShuttingDown atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() *Mux {
|
||||||
|
m := &Mux{
|
||||||
|
mux: http.NewServeMux(),
|
||||||
|
routes: new(RouteList),
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// HttpServeMux DO NOT USE it for routing, exposed only for edge cases.
|
||||||
|
func (m *Mux) HttpServeMux() *http.ServeMux {
|
||||||
|
return m.mux
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use will register middleware(s) with router stack
|
||||||
|
func (m *Mux) Use(h ...func(http.Handler) http.Handler) {
|
||||||
|
if m == nil {
|
||||||
|
panic("mux: func Use was called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.middlewares = append(m.middlewares, h...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET method route
|
||||||
|
func (m *Mux) GET(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodGet, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HEAD method route
|
||||||
|
func (m *Mux) HEAD(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodHead, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST method route
|
||||||
|
func (m *Mux) POST(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodPost, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PUT method route
|
||||||
|
func (m *Mux) PUT(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodPut, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH method route
|
||||||
|
func (m *Mux) PATCH(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodPatch, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE method route
|
||||||
|
func (m *Mux) DELETE(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
m.handle(http.MethodDelete, pattern, h, mw...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CONNECT method route
|
||||||
|
func (m *Mux) CONNECT(pattern string, h http.HandlerFunc) {
|
||||||
|
m.handle(http.MethodConnect, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OPTIONS method route
|
||||||
|
func (m *Mux) OPTIONS(pattern string, h http.HandlerFunc) {
|
||||||
|
m.handle(http.MethodOptions, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TRACE method route
|
||||||
|
func (m *Mux) TRACE(pattern string, h http.HandlerFunc) {
|
||||||
|
m.handle(http.MethodTrace, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle registers the handler for the given pattern.
|
||||||
|
// If the given pattern conflicts, with one that is already registered, HandleFunc
|
||||||
|
// panics.
|
||||||
|
func (m *Mux) handle(method, pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||||
|
if m == nil {
|
||||||
|
panic("mux: func Handle() was called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(pattern) == "" {
|
||||||
|
panic("mux: pattern cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.HasPrefix(pattern, "/") {
|
||||||
|
pattern = "/" + pattern
|
||||||
|
}
|
||||||
|
|
||||||
|
path := fmt.Sprintf("%s %s", method, pattern)
|
||||||
|
if len(mw) > 0 {
|
||||||
|
m.mux.Handle(path, stack(h, copyMW(m.middlewares, mw)))
|
||||||
|
} else {
|
||||||
|
m.mux.Handle(path, stack(h, m.middlewares))
|
||||||
|
}
|
||||||
|
|
||||||
|
m.routes.Add(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// With adds inline middlewares for an endpoint handler.
|
||||||
|
func (m *Mux) With(mw ...func(http.Handler) http.Handler) *Mux {
|
||||||
|
im := &Mux{
|
||||||
|
mux: m.mux,
|
||||||
|
middlewares: copyMW(m.middlewares, mw),
|
||||||
|
routes: m.routes,
|
||||||
|
}
|
||||||
|
|
||||||
|
return im
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group adds a new inline-Router along the current routing
|
||||||
|
// path, with a fresh middleware stack for the inline-Router.
|
||||||
|
func (m *Mux) Group(fn func(grp *Mux)) {
|
||||||
|
if m == nil {
|
||||||
|
panic("mux: Group() called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if fn == nil {
|
||||||
|
panic("mux: Group() requires callback")
|
||||||
|
}
|
||||||
|
|
||||||
|
im := m.With()
|
||||||
|
fn(im)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
|
if m == nil {
|
||||||
|
panic("mux: method ServeHTTP called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.mux.ServeHTTP(w, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) PrintRoutes(w io.Writer) {
|
||||||
|
for _, route := range m.routes.All() {
|
||||||
|
w.Write([]byte(route))
|
||||||
|
w.Write([]byte("\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) RouteList() []string {
|
||||||
|
return m.routes.All()
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyMW(a []func(http.Handler) http.Handler, b []func(http.Handler) http.Handler) []func(http.Handler) http.Handler {
|
||||||
|
if len(b) > 0 {
|
||||||
|
return slices.Concat(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
mws := make([]func(http.Handler) http.Handler, len(a))
|
||||||
|
copy(mws, a)
|
||||||
|
return mws
|
||||||
|
}
|
||||||
341
mux_test.go
Normal file
341
mux_test.go
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRouterGET(t *testing.T) {
|
||||||
|
m := New()
|
||||||
|
m.GET("/test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "GET test")
|
||||||
|
})
|
||||||
|
|
||||||
|
ts := httptest.NewServer(m)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
resp, err := http.Get(ts.URL + "/test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Errorf("Expected status OK; got %v", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "GET test"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterPOST(t *testing.T) {
|
||||||
|
m := New()
|
||||||
|
m.POST("/test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "POST test")
|
||||||
|
})
|
||||||
|
|
||||||
|
ts := httptest.NewServer(m)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
resp, err := http.Post(ts.URL+"/test", "text/plain", strings.NewReader("test data"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making POST request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Errorf("Expected status OK; got %v", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "POST test"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterWith(t *testing.T) {
|
||||||
|
m := New()
|
||||||
|
|
||||||
|
middleware := func(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("X-Test", "middleware")
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
m.With(middleware).GET("/test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "GET with middleware")
|
||||||
|
})
|
||||||
|
|
||||||
|
ts := httptest.NewServer(m)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
resp, err := http.Get(ts.URL + "/test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.Header.Get("X-Test") != "middleware" {
|
||||||
|
t.Errorf("Expected header X-Test to be 'middleware'; got %q", resp.Header.Get("X-Test"))
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "GET with middleware"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterGroup(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
|
||||||
|
var groupCalled bool
|
||||||
|
|
||||||
|
r.Group(func(g *Mux) {
|
||||||
|
groupCalled = true
|
||||||
|
g.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "Group route")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
if !groupCalled {
|
||||||
|
t.Error("Expected Group callback to be called")
|
||||||
|
}
|
||||||
|
|
||||||
|
ts := httptest.NewServer(r)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
resp, err := http.Get(ts.URL + "/group")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Errorf("Expected status OK; got %v", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "Group route"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterResource(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
|
||||||
|
r.Resource("/users",
|
||||||
|
func(res *Resource) {
|
||||||
|
res.Index(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "All users")
|
||||||
|
})
|
||||||
|
|
||||||
|
res.View(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := r.PathValue("id")
|
||||||
|
fmt.Fprintf(w, "User %s", id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
ts := httptest.NewServer(r)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
// Test Index
|
||||||
|
resp, err := http.Get(ts.URL + "/users")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "All users"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test Show
|
||||||
|
resp, err = http.Get(ts.URL + "/users/123")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
body, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected = "User 123"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetParams(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
|
||||||
|
r.GET("/users/{id}/posts/{post_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userId := r.PathValue("id")
|
||||||
|
postId := r.PathValue("post_id")
|
||||||
|
fmt.Fprintf(w, "User: %s, Post: %s", userId, postId)
|
||||||
|
})
|
||||||
|
|
||||||
|
ts := httptest.NewServer(r)
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
resp, err := http.Get(ts.URL + "/users/123/posts/456")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error making GET request: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error reading response body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := "User: 123, Post: 456"
|
||||||
|
if string(body) != expected {
|
||||||
|
t.Errorf("Expected body %q; got %q", expected, string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStack(t *testing.T) {
|
||||||
|
var calls []string
|
||||||
|
|
||||||
|
middleware1 := func(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls = append(calls, "middleware1 before")
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
calls = append(calls, "middleware1 after")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
middleware2 := func(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls = append(calls, "middleware2 before")
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
calls = append(calls, "middleware2 after")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls = append(calls, "handler")
|
||||||
|
})
|
||||||
|
|
||||||
|
middlewares := []func(http.Handler) http.Handler{middleware1, middleware2}
|
||||||
|
stacked := stack(handler, middlewares)
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
|
||||||
|
stacked.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
expected := []string{
|
||||||
|
"middleware1 before",
|
||||||
|
"middleware2 before",
|
||||||
|
"handler",
|
||||||
|
"middleware2 after",
|
||||||
|
"middleware1 after",
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(calls) != len(expected) {
|
||||||
|
t.Errorf("Expected %d calls; got %d", len(expected), len(calls))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, call := range calls {
|
||||||
|
if i < len(expected) && call != expected[i] {
|
||||||
|
t.Errorf("Expected call %d to be %q; got %q", i, expected[i], call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterPanic(t *testing.T) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r == nil {
|
||||||
|
t.Error("Expected panic but none occurred")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
var r *Mux
|
||||||
|
r.GET("/", func(w http.ResponseWriter, r *http.Request) {})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkRouterSimple-12 1125854 1058 ns/op 1568 B/op 17 allocs/op
|
||||||
|
func BenchmarkRouterSimple(b *testing.B) {
|
||||||
|
m := New()
|
||||||
|
|
||||||
|
for i := range 10000 {
|
||||||
|
m.GET("/"+strconv.Itoa(i), func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "Hello from "+strconv.Itoa(i))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
source := rand.NewSource(time.Now().UnixNano())
|
||||||
|
r := rand.New(source)
|
||||||
|
|
||||||
|
// Generate a random integer between 0 and 99 (inclusive)
|
||||||
|
rn := r.Intn(10000)
|
||||||
|
|
||||||
|
for b.Loop() {
|
||||||
|
req, _ := http.NewRequest(http.MethodGet, "/"+strconv.Itoa(rn), nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
m.ServeHTTP(w, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkRouterWithMiddleware-12 14761327 68.70 ns/op 18 B/op 0 allocs/op
|
||||||
|
func BenchmarkRouterWithMiddleware(b *testing.B) {
|
||||||
|
m := New()
|
||||||
|
|
||||||
|
middleware := func(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Use(middleware, middleware)
|
||||||
|
|
||||||
|
m.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "Hello")
|
||||||
|
})
|
||||||
|
|
||||||
|
req, _ := http.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
for b.Loop() {
|
||||||
|
m.ServeHTTP(w, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
224
resource.go
224
resource.go
@@ -6,28 +6,158 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Resource is a resourceful route provides a mapping between HTTP verbs and URLs and controller actions.
|
|
||||||
// By convention, each action also maps to particular CRUD operations in a database.
|
|
||||||
// A single entry in the routing file, such as
|
|
||||||
// Index route
|
|
||||||
//
|
|
||||||
// GET /resource-name # index route
|
|
||||||
//
|
|
||||||
// GET /resource-name/new # create resource page
|
|
||||||
//
|
|
||||||
// POST /resource-name # create resource post
|
|
||||||
//
|
|
||||||
// GET /resource-name/:id # view resource
|
|
||||||
//
|
|
||||||
// GET /resource-name/:id/edit # edit resource
|
|
||||||
//
|
|
||||||
// PUT /resource-name/:id # update resource
|
|
||||||
//
|
|
||||||
// DELETE /resource-name/:id # delete resource
|
|
||||||
type Resource struct {
|
type Resource struct {
|
||||||
mux *http.ServeMux
|
mux *http.ServeMux
|
||||||
pattern string
|
pattern string
|
||||||
middlewares []func(http.Handler) http.Handler
|
middlewares []func(http.Handler) http.Handler
|
||||||
|
routes *RouteList
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resource routes mapping by using HTTP verbs
|
||||||
|
// - GET /pattern view all resources
|
||||||
|
// - GET /pattern/create new resource view
|
||||||
|
// - POST /pattern create a new resource
|
||||||
|
// - GET /pattern/:id view a resource
|
||||||
|
// - PUT /pattern/:id update a resource
|
||||||
|
// - PATCH /pattern/:id partial update a resource
|
||||||
|
// - DELETE /resource/:id delete a resource
|
||||||
|
func (m *Mux) Resource(pattern string, fn func(res *Resource), mw ...func(http.Handler) http.Handler) {
|
||||||
|
if m == nil {
|
||||||
|
panic("mux: Resource() called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(pattern) == "" {
|
||||||
|
panic("mux: Resource() requires a patter to work")
|
||||||
|
}
|
||||||
|
|
||||||
|
if fn == nil {
|
||||||
|
panic("mux: Resource() requires callback")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn(&Resource{
|
||||||
|
mux: m.mux,
|
||||||
|
pattern: pattern,
|
||||||
|
middlewares: copyMW(m.middlewares, mw),
|
||||||
|
routes: m.routes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index of all resource.
|
||||||
|
//
|
||||||
|
// GET /pattern
|
||||||
|
func (res *Resource) Index(h http.HandlerFunc) {
|
||||||
|
res.routes.Add(http.MethodGet + " " + res.pattern)
|
||||||
|
res.handlerFunc(http.MethodGet, res.pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateView new resource
|
||||||
|
//
|
||||||
|
// GET /pattern/create
|
||||||
|
func (res *Resource) CreateView(h http.HandlerFunc) {
|
||||||
|
p := suffixIt(res.pattern, "create")
|
||||||
|
res.routes.Add(http.MethodGet + " " + p)
|
||||||
|
res.handlerFunc(http.MethodGet, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new resource
|
||||||
|
//
|
||||||
|
// POST /pattern/create
|
||||||
|
func (res *Resource) Create(h http.HandlerFunc) {
|
||||||
|
res.routes.Add(http.MethodPost + " " + res.pattern)
|
||||||
|
res.handlerFunc(http.MethodPost, res.pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// View a resource
|
||||||
|
//
|
||||||
|
// GET /pattern/:id
|
||||||
|
func (res *Resource) View(h http.HandlerFunc) {
|
||||||
|
p := suffixIt(res.pattern, "{id}")
|
||||||
|
res.routes.Add(http.MethodGet + " " + p)
|
||||||
|
res.handlerFunc(http.MethodGet, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update a resource
|
||||||
|
//
|
||||||
|
// PUT /pattern/:id
|
||||||
|
func (res *Resource) Update(h http.HandlerFunc) {
|
||||||
|
p := suffixIt(res.pattern, "{id}")
|
||||||
|
res.routes.Add(http.MethodPut + " " + p)
|
||||||
|
res.handlerFunc(http.MethodPut, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePartial resource info
|
||||||
|
// PATCH /pattern/:id
|
||||||
|
func (res *Resource) UpdatePartial(h http.HandlerFunc) {
|
||||||
|
p := suffixIt(res.pattern, "{id}")
|
||||||
|
res.routes.Add(http.MethodPatch + " " + p)
|
||||||
|
res.handlerFunc(http.MethodPatch, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete a resource
|
||||||
|
//
|
||||||
|
// DELETE /pattern/:id
|
||||||
|
func (res *Resource) Delete(h http.HandlerFunc) {
|
||||||
|
p := suffixIt(res.pattern, "{id}")
|
||||||
|
res.routes.Add(http.MethodDelete + " " + p)
|
||||||
|
res.handlerFunc(http.MethodDelete, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandleGET on /group-pattern/:id/pattern
|
||||||
|
func (res *Resource) HandleGET(pattern string, h http.HandlerFunc) {
|
||||||
|
res.handle(http.MethodGet, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandlePOST on /group-pattern/:id/pattern
|
||||||
|
func (res *Resource) HandlePOST(pattern string, h http.HandlerFunc) {
|
||||||
|
res.handle(http.MethodPost, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandlePUT on /group-pattern/:id/pattern
|
||||||
|
func (res *Resource) HandlePUT(pattern string, h http.HandlerFunc) {
|
||||||
|
res.handle(http.MethodPut, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandlePATCH on /group-pattern/:id/pattern
|
||||||
|
func (res *Resource) HandlePATCH(pattern string, h http.HandlerFunc) {
|
||||||
|
res.handle(http.MethodPatch, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandleDELETE on /group-pattern/:id/pattern
|
||||||
|
func (res *Resource) HandleDELETE(pattern string, h http.HandlerFunc) {
|
||||||
|
res.handle(http.MethodDelete, pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (res *Resource) handle(method string, pattern string, h http.HandlerFunc) {
|
||||||
|
if !strings.HasPrefix(pattern, "/") {
|
||||||
|
pattern = "/" + pattern
|
||||||
|
}
|
||||||
|
p := suffixIt(res.pattern, "{id}"+pattern)
|
||||||
|
res.routes.Add(method + " " + p)
|
||||||
|
res.handlerFunc(method, p, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handlerFunc registers the handler function for the given pattern.
|
||||||
|
// If the given pattern conflicts, with one that is already registered, HandleFunc
|
||||||
|
// panics.
|
||||||
|
func (res *Resource) handlerFunc(method, pattern string, h http.HandlerFunc) {
|
||||||
|
if res == nil {
|
||||||
|
panic("serve: func handlerFunc() was called on nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.mux == nil {
|
||||||
|
panic("serve: router mux is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
path := fmt.Sprintf("%s %s", method, pattern)
|
||||||
|
res.mux.Handle(path, stack(h, res.middlewares))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use will register middleware(s) on Router stack.
|
||||||
|
func (res *Resource) Use(middlewares ...func(http.Handler) http.Handler) {
|
||||||
|
if res == nil {
|
||||||
|
panic("serve: func Use was called on nil")
|
||||||
|
}
|
||||||
|
res.middlewares = append(res.middlewares, middlewares...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func suffixIt(str, suffix string) string {
|
func suffixIt(str, suffix string) string {
|
||||||
@@ -39,61 +169,3 @@ func suffixIt(str, suffix string) string {
|
|||||||
p.WriteString(suffix)
|
p.WriteString(suffix)
|
||||||
return p.String()
|
return p.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Index is GET /resource-name
|
|
||||||
func (r *Resource) Index(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodGet, r.pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// New is GET /resource-name/new
|
|
||||||
func (r *Resource) New(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodGet, suffixIt(r.pattern, "new"), h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create is POST /resource-name
|
|
||||||
func (r *Resource) Create(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPost, r.pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show is GET /resource-name/:id
|
|
||||||
func (r *Resource) Show(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodGet, suffixIt(r.pattern, "{id}"), h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update is PUT /resource-name/:id
|
|
||||||
func (r *Resource) Update(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPut, suffixIt(r.pattern, "{id}"), h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PartialUpdate is PATCH /resource-name/:id
|
|
||||||
func (r *Resource) PartialUpdate(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPatch, suffixIt(r.pattern, "{id}"), h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resource) Destroy(h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodDelete, suffixIt(r.pattern, "{id}"), h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// handlerFunc registers the handler function for the given pattern.
|
|
||||||
// If the given pattern conflicts, with one that is already registered, HandleFunc
|
|
||||||
// panics.
|
|
||||||
func (r *Resource) handlerFunc(method, pattern string, h http.HandlerFunc) {
|
|
||||||
if r == nil {
|
|
||||||
panic("serve: func handlerFunc() was called on nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.mux == nil {
|
|
||||||
panic("serve: router mux is nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
path := fmt.Sprintf("%s %s", method, pattern)
|
|
||||||
r.mux.Handle(path, stack(r.middlewares, h))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use will register middleware(s) on Router stack.
|
|
||||||
func (r *Resource) Use(middlewares ...func(http.Handler) http.Handler) {
|
|
||||||
if r == nil {
|
|
||||||
panic("serve: func Use was called on nil")
|
|
||||||
}
|
|
||||||
r.middlewares = append(r.middlewares, middlewares...)
|
|
||||||
}
|
|
||||||
|
|||||||
51
route.go
Normal file
51
route.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RouteList struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
routes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *RouteList) Add(item string) {
|
||||||
|
if s == nil {
|
||||||
|
slog.Warn("failed on Add, RouteList is nil")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
s.routes = append(s.routes, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *RouteList) Get(index int) (string, error) {
|
||||||
|
if s == nil {
|
||||||
|
slog.Warn("failed on Get, RouteList is nil")
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
|
if index < 0 || index >= len(s.routes) {
|
||||||
|
return "0", fmt.Errorf("index out of bounds")
|
||||||
|
}
|
||||||
|
return s.routes[index], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *RouteList) All() []string {
|
||||||
|
if s == nil {
|
||||||
|
slog.Warn("failed on All, RouteList is nil")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
|
return s.routes
|
||||||
|
}
|
||||||
162
router.go
162
router.go
@@ -1,162 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Router is a wrapper around the go's standard http.ServeMux.
|
|
||||||
// It's a lean wrapper with methods to make routing easier
|
|
||||||
type Router struct {
|
|
||||||
mux *http.ServeMux
|
|
||||||
middlewares []func(http.Handler) http.Handler
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRouter() *Router {
|
|
||||||
r := &Router{
|
|
||||||
mux: http.NewServeMux(),
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use will register middleware(s) with router stack
|
|
||||||
func (r *Router) Use(h ...func(http.Handler) http.Handler) {
|
|
||||||
if r == nil {
|
|
||||||
panic("mux: func Use was called on nil")
|
|
||||||
}
|
|
||||||
r.middlewares = append(r.middlewares, h...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GET method route
|
|
||||||
func (r *Router) GET(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodGet, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// HEAD method route
|
|
||||||
func (r *Router) HEAD(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodHead, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// POST method route
|
|
||||||
func (r *Router) POST(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPost, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PUT method route
|
|
||||||
func (r *Router) PUT(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPut, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PATCH method route
|
|
||||||
func (r *Router) PATCH(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodPatch, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DELETE method route
|
|
||||||
func (r *Router) DELETE(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodDelete, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CONNECT method route
|
|
||||||
func (r *Router) CONNECT(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodConnect, pattern, h)
|
|
||||||
} // OPTIONS method route
|
|
||||||
func (r *Router) OPTIONS(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodOptions, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TRACE method route
|
|
||||||
func (r *Router) TRACE(pattern string, h http.HandlerFunc) {
|
|
||||||
r.handlerFunc(http.MethodTrace, pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// HandleFunc registers the handler function for the given pattern.
|
|
||||||
// If the given pattern conflicts, with one that is already registered, HandleFunc
|
|
||||||
// panics.
|
|
||||||
func (r *Router) handlerFunc(method, pattern string, h http.HandlerFunc) {
|
|
||||||
if r == nil {
|
|
||||||
panic("mux: func Handle() was called on nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
path := fmt.Sprintf("%s %s", method, pattern)
|
|
||||||
r.mux.Handle(path, stack(r.middlewares, h))
|
|
||||||
}
|
|
||||||
|
|
||||||
// With adds inline middlewares for an endpoint handler.
|
|
||||||
func (r *Router) With(middleware ...func(http.Handler) http.Handler) *Router {
|
|
||||||
mws := make([]func(http.Handler) http.Handler, len(r.middlewares))
|
|
||||||
copy(mws, r.middlewares)
|
|
||||||
mws = append(mws, middleware...)
|
|
||||||
|
|
||||||
im := &Router{
|
|
||||||
mux: r.mux,
|
|
||||||
middlewares: mws,
|
|
||||||
}
|
|
||||||
|
|
||||||
return im
|
|
||||||
}
|
|
||||||
|
|
||||||
// Group adds a new inline-Router along the current routing
|
|
||||||
// path, with a fresh middleware stack for the inline-Router.
|
|
||||||
func (r *Router) Group(fn func(grp *Router)) {
|
|
||||||
if r == nil {
|
|
||||||
panic("mux: Resource() called on nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if fn == nil {
|
|
||||||
panic("mux: Group() requires callback")
|
|
||||||
}
|
|
||||||
|
|
||||||
im := r.With()
|
|
||||||
fn(im)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resource resourceful route provides a mapping between HTTP verbs for given the pattern
|
|
||||||
func (r *Router) Resource(pattern string, fn func(resource *Resource)) {
|
|
||||||
if r == nil {
|
|
||||||
panic("mux: Resource() called on nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(pattern) == "" {
|
|
||||||
panic("mux: Resource() requires a patter to work")
|
|
||||||
}
|
|
||||||
|
|
||||||
if fn == nil {
|
|
||||||
panic("mux: Resource() requires callback")
|
|
||||||
}
|
|
||||||
|
|
||||||
mws := make([]func(http.Handler) http.Handler, len(r.middlewares))
|
|
||||||
copy(mws, r.middlewares)
|
|
||||||
fn(&Resource{
|
|
||||||
mux: r.mux,
|
|
||||||
pattern: pattern,
|
|
||||||
middlewares: mws,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
if r == nil {
|
|
||||||
panic("mux: method ServeHTTP called on nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.mux.ServeHTTP(w, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: proxy for aws lambda
|
|
||||||
|
|
||||||
// stack middlewares(http handler) in order they are passed (FIFO)
|
|
||||||
func stack(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
|
|
||||||
// Return ahead of time if there aren't any middlewares for the chain
|
|
||||||
if len(middlewares) == 0 {
|
|
||||||
return endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
// wrap the end handler with the middleware chain
|
|
||||||
h := middlewares[len(middlewares)-1](endpoint)
|
|
||||||
for i := len(middlewares) - 2; i >= 0; i-- {
|
|
||||||
h = middlewares[i](h)
|
|
||||||
}
|
|
||||||
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ServeCB func(srv *http.Server) error
|
|
||||||
|
|
||||||
// Serve with graceful shutdown
|
|
||||||
func (r *Router) Serve(cb ServeCB) {
|
|
||||||
// catch all options
|
|
||||||
// lets get it thorugh all middlewares
|
|
||||||
r.OPTIONS("/", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Length", "0")
|
|
||||||
if r.ContentLength != 0 {
|
|
||||||
// Read up to 4KB of OPTIONS body (as mentioned in the
|
|
||||||
// spec as being reserved for future use), but anything
|
|
||||||
// over that is considered a waste of server resources
|
|
||||||
// (or an attack) and we abort and close the connection,
|
|
||||||
// courtesy of MaxBytesReader's EOF behavior.
|
|
||||||
mb := http.MaxBytesReader(w, r.Body, 4<<10)
|
|
||||||
io.Copy(io.Discard, mb)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
srv := &http.Server{
|
|
||||||
Handler: r,
|
|
||||||
}
|
|
||||||
|
|
||||||
idleConnsClosed := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
sigint := make(chan os.Signal, 1)
|
|
||||||
signal.Notify(sigint, os.Interrupt)
|
|
||||||
<-sigint
|
|
||||||
|
|
||||||
// We received an interrupt signal, shut down.
|
|
||||||
if err := srv.Shutdown(context.Background()); err != nil {
|
|
||||||
// Error from closing listeners, or context timeout:
|
|
||||||
slog.Error("server shutdown error", "error", err)
|
|
||||||
} else {
|
|
||||||
slog.Info("server shutdown")
|
|
||||||
}
|
|
||||||
close(idleConnsClosed)
|
|
||||||
}()
|
|
||||||
|
|
||||||
if err := cb(srv); !errors.Is(err, http.ErrServerClosed) {
|
|
||||||
// Error starting or closing listener:
|
|
||||||
slog.Error("start server error", "error", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-idleConnsClosed
|
|
||||||
}
|
|
||||||
78
serve.go
Normal file
78
serve.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServeCB func(srv *http.Server) error
|
||||||
|
|
||||||
|
const (
|
||||||
|
shutdownDelay = time.Second * 10
|
||||||
|
shutdownHardDelay = time.Second * 5
|
||||||
|
drainDelay = time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// Serve with graceful shutdown
|
||||||
|
func (m *Mux) Serve(cb ServeCB) {
|
||||||
|
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
// catch all options
|
||||||
|
// lets get it thorugh all middlewares
|
||||||
|
m.OPTIONS("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Length", "0")
|
||||||
|
if r.ContentLength != 0 {
|
||||||
|
// Read up to 4KB of OPTIONS body (as mentioned in the
|
||||||
|
// spec as being reserved for future use), but anything
|
||||||
|
// over that is considered a waste of server resources
|
||||||
|
// (or an attack) and we abort and close the connection,
|
||||||
|
// courtesy of MaxBytesReader's EOF behavior.
|
||||||
|
mb := http.MaxBytesReader(w, r.Body, 4<<10)
|
||||||
|
io.Copy(io.Discard, mb)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
srvCtx, cancelSrvCtx := context.WithCancel(context.Background())
|
||||||
|
srv := &http.Server{
|
||||||
|
Handler: m,
|
||||||
|
BaseContext: func(_ net.Listener) context.Context {
|
||||||
|
return srvCtx
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
if err := cb(srv); !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait for interrupt signal
|
||||||
|
<-rootCtx.Done()
|
||||||
|
|
||||||
|
stop()
|
||||||
|
m.IsShuttingDown.Store(true)
|
||||||
|
slog.Info("received interrupt singal, shutting down")
|
||||||
|
time.Sleep(drainDelay)
|
||||||
|
slog.Info("readiness check propagated, now waiting for ongoing requests to finish.")
|
||||||
|
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownDelay)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
err := srv.Shutdown(shutdownCtx)
|
||||||
|
cancelSrvCtx()
|
||||||
|
if err != nil {
|
||||||
|
log.Println("failed to wait for ongoing requests to finish, waiting for forced cancellation")
|
||||||
|
time.Sleep(shutdownHardDelay)
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("seerver shut down gracefully")
|
||||||
|
}
|
||||||
19
stack.go
Normal file
19
stack.go
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
// stack middlewares(http handler) in order they are passed (FIFO)
|
||||||
|
func stack(endpoint http.Handler, middlewares []func(http.Handler) http.Handler) http.Handler {
|
||||||
|
// Return ahead of time if there aren't any middlewares for the chain
|
||||||
|
if len(middlewares) == 0 {
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrap the end handler with the middleware chain
|
||||||
|
h := middlewares[len(middlewares)-1](endpoint)
|
||||||
|
for i := len(middlewares) - 2; i >= 0; i-- {
|
||||||
|
h = middlewares[i](h)
|
||||||
|
}
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user