Skip to content

Instantly share code, notes, and snippets.

@markeissler
Forked from bennAH/mux_handlers.go
Created April 17, 2020 17:04
Show Gist options
  • Save markeissler/3c408d2c0e4f28e86ff737183f08b8fc to your computer and use it in GitHub Desktop.
Save markeissler/3c408d2c0e4f28e86ff737183f08b8fc to your computer and use it in GitHub Desktop.
gorilla mux - multiple handlers
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler) // no auth
r.HandleFunc("/about", AboutHandler) // no auth
r.HandleFunc("/user/", UserHandler) // auth needed
r.HandleFunc("/user/account", UserAccountHandler) // auth needed
smx := http.NewServeMux()
smx.Handle("/", MH{r})
smx.Handle("/user/", AH{r})
s := &http.Server{Addr: ":2022", Handler: smx}
s.ListenAndServe()
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Home")
}
func AboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "About")
}
func UserHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "User")
}
func UserAccountHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "User Account")
}
type AH struct {
http.Handler
}
func (ah AH) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "auth needed - ")
ah.Handler.ServeHTTP(w, r)
}
type MH struct {
http.Handler
}
func (mh MH) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "no auth - ")
mh.Handler.ServeHTTP(w, r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment