-
-
Save markeissler/3c408d2c0e4f28e86ff737183f08b8fc to your computer and use it in GitHub Desktop.
gorilla mux - multiple handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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