-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
48 lines (39 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
package main
import (
"log"
"net/http"
"time"
rice "github.com/GeertJohan/go.rice"
)
func main() {
// Define the rice box with the frontend client static files.
appBox, err := rice.FindBox("client/build")
if err != nil {
log.Fatal(err)
}
// Define ping endpoint that responds with pong.
http.HandleFunc("/api/ping", pingHandler())
// Serve static files
http.Handle("/static/", http.FileServer(appBox.HTTPBox()))
// Serve SPA (Single Page Application)
http.HandleFunc("/", serveAppHandler(appBox))
log.Println("Server starting at port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func pingHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Pong"))
}
}
func serveAppHandler(app *rice.Box) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
indexFile, err := app.Open("index.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
http.ServeContent(w, r, "index.html", time.Time{}, indexFile)
}
}