-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (79 loc) · 1.88 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
package main
import (
"log"
"net/http"
"net/url"
"regexp"
"strconv"
"time"
)
var pathPattern = regexp.MustCompile(`^/(?:` +
// version
`(\d+(?:\.\d+){2}(?:-[^/]+)?)|` +
// commit
`(?:sha-)([^/]+)|` +
// branchOrTag
`([^/]+)` +
`)$`)
const (
versionIndex = iota + 1
commitIndex
branchOrTagIndex
)
var client = &http.Client{
Transport: &http.Transport{
TLSHandshakeTimeout: 5 * time.Second,
IdleConnTimeout: 60 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
MaxIdleConns: 5,
MaxIdleConnsPerHost: 5,
MaxConnsPerHost: 5,
},
}
func handle(w http.ResponseWriter, r *http.Request) {
match := pathPattern.FindStringSubmatch(r.URL.Path)
if match == nil {
http.NotFound(w, r)
return
}
if !(r.Method == http.MethodHead || r.Method == http.MethodGet) {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var (
head string
shouldRedirect bool
)
switch true {
case match[versionIndex] != "":
head = "v" + match[versionIndex]
case match[commitIndex] != "":
head = match[commitIndex]
shouldRedirect = true
case match[branchOrTagIndex] != "":
head = match[branchOrTagIndex]
shouldRedirect = true
default:
panic("unreachable")
}
schemaURL := "https://raw.githubusercontent.com/linearmouse/linearmouse/" + url.PathEscape(head) + "/Documentation/Configuration.json"
if shouldRedirect {
http.Redirect(w, r, schemaURL, http.StatusTemporaryRedirect)
return
}
schema, err := getSchema(schemaURL)
switch err {
case nil:
case errSchemaNotFound:
http.NotFound(w, r)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(schema)))
w.Write(schema)
}
func main() {
http.HandleFunc("/", handle)
log.Fatal(http.ListenAndServe(":3000", nil))
}