-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathmain.go
113 lines (103 loc) · 2.38 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
113
// ex4.14 caches a github repository's issues and serves a barebones
// representation of them over http.
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"strconv"
"strings"
)
var issueListTemplate = template.Must(template.New("issueList").Parse(`
<h1>{{.Issues | len}} issues</h1>
<table>
<tr style='text-align: left'>
<th>#</th>
<th>State</th>
<th>User</th>
<th>Title</th>
</tr>
{{range .Issues}}
<tr>
<td><a href='{{.CacheURL}}'>{{.Number}}</td>
<td>{{.State}}</td>
<td><a href='{{.User.HTMLURL}}'>{{.User.Login}}</a></td>
<td><a href='{{.CacheURL}}'>{{.Title}}</a></td>
</tr>
{{end}}
</table>
`))
var issueTemplate = template.Must(template.New("issue").Parse(`
<h1>{{.Title}}</h1>
<dl>
<dt>user</dt>
<dd><a href='{{.User.HTMLURL}}'>{{.User.Login}}</a></dd>
<dt>state</dt>
<dd>{{.State}}</dd>
</dl>
<p>{{.Body}}</p>
`))
type IssueCache struct {
Issues []Issue
IssuesByNumber map[int]Issue
}
func NewIssueCache(owner, repo string) (ic IssueCache, err error) {
issues, err := GetIssues(owner, repo)
if err != nil {
return
}
ic.Issues = issues
ic.IssuesByNumber = make(map[int]Issue, len(issues))
for _, issue := range issues {
ic.IssuesByNumber[issue.Number] = issue
}
return
}
func logNonNil(v interface{}) {
if v != nil {
log.Print(v)
}
}
func (ic IssueCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
pathParts := strings.SplitN(r.URL.Path, "/", -1)
if len(pathParts) < 3 || pathParts[2] == "" {
logNonNil(issueListTemplate.Execute(w, ic))
return
}
numStr := pathParts[2]
num, err := strconv.Atoi(numStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, err := w.Write([]byte(fmt.Sprintf("Issue number isn't a number: '%s'", numStr)))
if err != nil {
log.Printf("Error writing response for %s: %s", r, err)
}
return
}
issue, ok := ic.IssuesByNumber[num]
if !ok {
w.WriteHeader(http.StatusNotFound)
_, err := w.Write([]byte(fmt.Sprintf("No issue '%d'", num)))
if err != nil {
log.Printf("Error writing response for %s: %s", r, err)
}
return
}
logNonNil(issueTemplate.Execute(w, issue))
}
func main() {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: githubserver OWNER REPO")
os.Exit(1)
}
owner := os.Args[1]
repo := os.Args[2]
issueCache, err := NewIssueCache(owner, repo)
if err != nil {
log.Fatal(err)
}
http.Handle("/", issueCache)
log.Fatal(http.ListenAndServe(":8080", nil))
}