-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
39 lines (30 loc) · 1.26 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"fmt"
"net/http"
"github.com/carbocation/interpose"
"github.com/carbocation/interpose/middleware"
"github.com/gorilla/mux"
)
func main() {
middle := interpose.New()
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
})
middle.UseHandler(router)
// Now we will define a sub-router that uses the BasicAuth middleware
// When you call any url starting with the path /protected, you will need to authenticate
protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the protected page!")
})
// Define middleware that pertains to the part of the site protected behind HTTP Auth
// and add the protected router to the protected middleware
protectedMiddlew := interpose.New()
protectedMiddlew.Use(middleware.BasicAuth("john", "doe"))
protectedMiddlew.UseHandler(protectedRouter)
// Add the protected middleware and its router to the main router
router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)
http.ListenAndServe(":3001", middle)
}