-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
82 lines (64 loc) · 1.97 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
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
73
74
75
76
77
78
79
80
81
82
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type profile struct {
Name string
Hobbies []string
}
func main() {
mux := http.NewServeMux()
v1Mux := http.NewServeMux()
v1Mux.HandleFunc("/profile", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "v1 Profile")
})
v1Mux.HandleFunc("/posts", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "v1 Posts")
})
v2Mux := http.NewServeMux()
v2Mux.HandleFunc("/profile", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "v2 Profile")
})
v2Mux.HandleFunc("/posts", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "v2 Posts")
})
mux.Handle("/v1/", http.StripPrefix("/v1", v1Mux))
mux.Handle("/v2/", http.StripPrefix("/v2", v2Mux))
mux.HandleFunc("/welcome", welcome)
mux.HandleFunc("/profile", getProfile)
loggedHandler := loggingMiddleware(mux)
// http.Handle("/", http.FileServer(http.Dir("/tmp")))
fs := http.FileServer(http.Dir("static"))
mux.Handle("/", fs)
if err := http.ListenAndServe(":8080", loggedHandler); err != nil {
log.Fatal(err)
}
}
func getProfile(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
profile := profile{
Name: "Steveen Echeverri",
Hobbies: []string{"Programming", "Design"},
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(profile); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// func ListenAndServe(addr string, handler Handler) error
func welcome(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to the GO server..")
}
func loggingMiddleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Got a %s request for: %v\n", r.Method, r.URL)
handler.ServeHTTP(w, r)
log.Printf("Handler finished processing request.")
})
}