Skip to content

Instantly share code, notes, and snippets.

@gocs
Last active April 22, 2023 03:31
Show Gist options
  • Save gocs/75d75fd9e9a1b185bf407c8c72d536a0 to your computer and use it in GitHub Desktop.
Save gocs/75d75fd9e9a1b185bf407c8c72d536a0 to your computer and use it in GitHub Desktop.
basic net/http compatible middleware
func main() {
r := chi.Router()
r.Use(Basic())
r.Use(Static("/static", "server2/static"))
http.ListenAndServe(":3000", r)
}
type Middleware func(next http.Handler) http.Handler
func Basic() Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
// Static serves static files
//
// pattern - string displayed on the URL (ie. "/static" in "localhost:8080/static")
// dir - string where the file is located relative to go.mod
//
// r.Use(Static("/static", "server2/static"))
func Static(pattern, dir string) Middleware {
fs := http.FileServer(http.Dir(dir))
h := http.StripPrefix(pattern+"/", fs)
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
_, after, ok1 := strings.Cut(r.URL.Path, "/")
before, _, ok2 := strings.Cut(after, "/")
rPath := "/" + before
if !ok1 || !ok2 || pattern != rPath {
next.ServeHTTP(w, r)
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment