-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (44 loc) · 934 Bytes
/
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
package main
import (
"embed"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
)
// embedded files
//go:embed content/*
var f embed.FS
const port = 8080 // port to run on
func main() {
// use enviroment variable for port if exists
envport, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
envport = port
}
// start
log.Println("welcome to amp")
log.Println("listening on http://localhost:" + strconv.Itoa(envport))
// register handler
http.HandleFunc("/", handler)
err = http.ListenAndServe("localhost:"+strconv.Itoa(envport), nil)
if err != nil {
log.Fatal(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
// index hack
if r.URL.Path == "/" {
r.URL.Path = "index.html"
}
fp := "content/" + strings.TrimPrefix(filepath.Clean(r.URL.Path), `/`)
p, err := f.ReadFile(fp)
if err != nil {
http.NotFound(w, r)
return
}
w.Write(p)
log.Println("served", fp)
}