Skip to content

Instantly share code, notes, and snippets.

@elkcityhazard
Last active January 2, 2025 02:00
Show Gist options
  • Save elkcityhazard/297dadb7ce6afc5d6aa7fda99562f0cf to your computer and use it in GitHub Desktop.
Save elkcityhazard/297dadb7ce6afc5d6aa7fda99562f0cf to your computer and use it in GitHub Desktop.
A basic go http webserver that uses my custom router implementation
package main
import (
"fmt"
"log"
"net/http"
"strings"
amrouter "github.com/elkcityhazard/am-router"
)
func main() {
rtr := amrouter.NewRouter()
rtr.PathToStaticDir = "/static"
rtr.AddRoute("GET", "/", http.HandlerFunc(homeHandler), homeMiddleWare)
rtr.AddRoute("GET", "(^/[\\w-]+)/?$", func(w http.ResponseWriter, r *http.Request) {
key := rtr.GetField(r, 0)
fmt.Fprint(w, key)
})
srv := &http.Server{
Addr: ":8080",
Handler: rtr,
}
fmt.Println("running")
if err := srv.ListenAndServe(); err != nil {
log.Panic(err)
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "home handler")
}
func homeMiddleWare(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("I am the home middleware")
next.ServeHTTP(w, r)
})
}
func addTrailingSlash(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("add trailing slash")
if !strings.HasSuffix(r.URL.Path, "/") {
http.Redirect(w, r.WithContext(r.Context()), r.URL.Path+"/", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment