-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
104 lines (84 loc) · 1.95 KB
/
handler.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
package gemini
import (
"fmt"
"log"
"net"
"net/url"
"strings"
)
type Request struct {
URL *url.URL
}
type Response struct {
Body net.Conn
Meta string
StatusCode int
StatusText string
}
func (r *Response) Write(b []byte) (int, error) {
err := r.SendStatus()
if err != nil {
log.Println(err)
return -1, err
}
return r.Body.Write(b)
}
func (r *Response) SetStatus(statusCode int, statusText string) {
r.StatusCode = statusCode
r.StatusText = statusText
}
func (r *Response) SendStatus() error {
if r.StatusText == "" {
r.StatusCode = StatusSuccess
r.StatusText = "text/gemini"
}
_, err := r.Body.Write([]byte(fmt.Sprintf("%d %s\r\n", r.StatusCode, r.StatusText)))
return err
}
type Handler interface {
ServeGemini(w *Response, r *Request)
}
type Handlerfunc func(*Response, *Request)
func (h Handlerfunc) ServeGemini(w *Response, r *Request) {
h(w, r)
}
type Path struct {
handler Handler
path string
}
type SimpleHandler struct {
pathHandler []Path
}
var DefaultHandler = new(SimpleHandler)
func (s *SimpleHandler) ServeGemini(w *Response, r *Request) {
u := r.URL.Path
if u == "" {
u = "/"
}
for _, h := range s.pathHandler {
if strings.HasPrefix(u, h.path) {
h.handler.ServeGemini(w, r)
return
}
}
}
func HandleFunc(p string, h func(*Response, *Request)) {
DefaultHandler.pathHandler = append(DefaultHandler.pathHandler, Path{handler: Handlerfunc(h), path: p})
}
func Handle(p string, h Handler) {
DefaultHandler.pathHandler = append(DefaultHandler.pathHandler, Path{handler: h, path: p})
}
func ListenAndServeTLS(addr string, certFile, keyFile string) error {
s := Server{Addr: addr, Handler: DefaultHandler}
return s.ListenAndServeTLS(certFile, keyFile)
}
func StripPrefix(prefix string, handler Handler) Handler {
if prefix == "" {
return handler
}
return Handlerfunc(func(w *Response, r *Request) {
path := strings.TrimPrefix(r.URL.Path, prefix)
r.URL.Path = path
handler.ServeGemini(w, r)
})
}