forked from shijuvar/go-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flowcontrol.go
58 lines (50 loc) · 1.44 KB
/
flowcontrol.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"log"
"net/http"
)
func middlewareFirst(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("MiddlewareFirst - Before Handler")
next.ServeHTTP(w, r)
log.Println("MiddlewareFirst - After Handler")
})
}
func middlewareSecond(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("MiddlewareSecond - Before Handler")
if r.URL.Path == "/message" {
if r.URL.Query().Get("password") == "pass123" {
log.Println("Authorized to the system")
next.ServeHTTP(w, r)
} else {
log.Println("Failed to authorize to the system")
return
}
} else {
next.ServeHTTP(w, r)
}
log.Println("MiddlewareSecond - After Handler")
})
}
func index(w http.ResponseWriter, r *http.Request) {
log.Println("Executing index Handler")
fmt.Fprintf(w, "Welcome")
}
func message(w http.ResponseWriter, r *http.Request) {
log.Println("Executing message Handler")
fmt.Fprintf(w, "HTTP Middleware is awesome")
}
func iconHandler(w http.ResponseWriter, r *http.Request) {
}
func main() {
http.HandleFunc("/favicon.ico", iconHandler)
http.Handle("/", middlewareFirst(middlewareSecond(http.HandlerFunc(index))))
http.Handle("/message", middlewareFirst(middlewareSecond(http.HandlerFunc(message))))
server := &http.Server{
Addr: ":8080",
}
log.Println("Listening...")
server.ListenAndServe()
}