-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
59 lines (47 loc) · 1.08 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
package main
import (
"fmt"
"net/http"
"strings"
"time"
)
func main() {
srv := &http.Server{
Addr: ":80",
Handler: router(),
IdleTimeout: time.Minute,
}
fmt.Println("Server is running on port ", srv.Addr)
srv.ListenAndServe()
}
func router() http.Handler {
mux := http.NewServeMux()
// index
mux.HandleFunc("/", indexHandler)
// static files
httpFS := http.FileServer(http.Dir("files/build"))
mux.Handle("/assets/", httpFS)
mux.Handle("/img/", httpFS)
// api
mux.HandleFunc("/api/v1/greeting", greetingAPI)
return mux
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, http.StatusText(http.StatusMethodNotAllowed))
return
}
if strings.HasPrefix(r.URL.Path, "/api") {
http.NotFound(w, r)
return
}
if r.URL.Path == "/favicon.ico" {
http.ServeFile(w, r, "files/build/favicon.ico")
return
}
http.ServeFile(w, r, "files/build/index.html")
}
func greetingAPI(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, there!"))
}