forked from shijuvar/go-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alice.go
72 lines (67 loc) · 1.34 KB
/
alice.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"io"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/justinas/alice"
)
func loggingHandler(next http.Handler) http.Handler {
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
panic(err)
}
return handlers.LoggingHandler(logFile, next)
}
func index(w http.ResponseWriter, r *http.Request) {
w.Header().Set(
"Content-Type",
"text/html",
)
io.WriteString(
w,
`<doctype html>
<html>
<head>
<title>Index</title>
</head>
<body>
Hello Gopher!
</body>
</html>`,
)
}
func about(w http.ResponseWriter, r *http.Request) {
w.Header().Set(
"Content-Type",
"text/html",
)
io.WriteString(
w,
`<doctype html>
<html>
<head>
<title>About</title>
</head>
<body>
Go Web development with HTTP Middleware
</body>
</html>`,
)
}
func iconHandler(w http.ResponseWriter, r *http.Request) {
}
func main() {
http.HandleFunc("/favicon.ico", iconHandler)
indexHandler := http.HandlerFunc(index)
aboutHandler := http.HandlerFunc(about)
commonHandlers := alice.New(loggingHandler, handlers.CompressHandler)
http.Handle("/", commonHandlers.ThenFunc(indexHandler))
http.Handle("/about", commonHandlers.ThenFunc(aboutHandler))
server := &http.Server{
Addr: ":8080",
}
log.Println("Listening...")
server.ListenAndServe()
}