-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
112 lines (93 loc) · 2.13 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
_ "embed"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
)
var (
addr = flag.String("http", "127.0.0.1:8080", "listen on http")
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
flag.Parse()
var rd io.Reader = os.Stdin
if flag.Arg(0) != "" {
file, err := os.Open(flag.Arg(0))
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
rd = file
}
data, err := io.ReadAll(rd)
if err != nil {
return fmt.Errorf("failed to read data: %w", err)
}
index := NewIndex()
dir, _ := filepath.Abs(".")
index.Parse(dir, data)
fmt.Printf("Listening on http://%v\n", *addr)
err = http.ListenAndServe(*addr, &Server{index})
if err != nil {
return fmt.Errorf("listening failed: %w", err)
}
return nil
}
type Server struct {
Index *Index
}
func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "" || r.URL.Path == "/" {
defaultPath := r.URL.Query().Get("path")
err := T.Execute(w, map[string]interface{}{
"StatCount": statCount,
"Stats": statSpecs,
"Files": server.Index.Files,
"DefaultPath": defaultPath,
})
if err != nil {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(os.Stderr, "%v\n", err)
}
return
}
if r.URL.Path == "/file" {
path := r.FormValue("path")
if path == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "No path specified.")
return
}
annotated, err := server.Index.LoadAnnotatedFile(path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "%v\n", err)
fmt.Fprintf(w, "Error: %v", err)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(annotated)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
return
}
w.WriteHeader(http.StatusNotFound)
}
//go:embed index.html
var indexTemplate string
var T = template.Must(template.New("").Funcs(template.FuncMap{
"mul": func(a, b int) int { return a * b },
}).Parse(indexTemplate))