-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
78 lines (66 loc) · 1.72 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
package main
import (
"embed"
"encoding/json"
"flag"
"io/fs"
"log"
"net/http"
"github.com/go-chi/chi/v5"
)
//go:embed all:build/**
var buildFS embed.FS
var (
addr = flag.String("addr", ":8080", "Bind addr to listen for request")
noLogin = flag.Bool("nologin", false, "Simulate no login on /me call")
)
func main() {
flag.Parse()
log.Printf("starting server at %s...", *addr)
if err := http.ListenAndServe(*addr, newRouter()); err != nil {
log.Fatalf("server exited: %s", err)
}
}
func newRouter() chi.Router {
appFS := mustSub("build")
nonAppServer := http.FileServer(http.FS(appFS))
appServer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
indexFile, _ := buildFS.ReadFile("build/app/index.html")
w.Write(indexFile)
})
r := chi.NewRouter()
r.Mount("/", nonAppServer)
r.Mount("/app", appServer)
r.Route("/api", func(r chi.Router) {
r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
log.Printf("PING received")
})
r.Get("/me", func(w http.ResponseWriter, r *http.Request) {
// Note: -nologin flag can be used to simulate error.
if *noLogin {
writeJSON(w, http.StatusUnauthorized, nil)
} else {
writeJSON(w, http.StatusOK, map[string]any{
"id": "yJIABar",
"name": "Bob Builder",
"picture": "https://www.gravatar.com/avatar?s=64",
"email": "[email protected]",
"username": "bobthebuilder",
})
}
})
})
return r
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func mustSub(subPath string) fs.FS {
f, err := fs.Sub(buildFS, subPath)
if err != nil {
panic(err)
}
return f
}