-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgemini.go
95 lines (84 loc) · 2.29 KB
/
gemini.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
// gemini server implementation, check out gemini://gemini.circumlunar.space/
// inspired by https://tildegit.org/solderpunk/molly-brown
//
// Example:
//
// package main
//
// import (
// "log"
//
// gemini "github.com/jackdoe/net-gemini"
// )
//
// func main() {
// gemini.HandleFunc("/example", func(w *gemini.Response, r *gemini.Request) {
// if len(r.URL.RawQuery) == 0 {
// w.SetStatus(gemini.StatusInput, "what is the answer to the ultimate question")
// } else {
// w.SetStatus(gemini.StatusSuccess, "text/gemini")
// answer := r.URL.RawQuery
// w.Write([]byte("HELLO: " + r.URL.Path + ", yes the answer is: " + answer))
// }
// })
//
// gemini.Handle("/", gemini.FileServer(*root))
// log.Fatal(gemini.ListenAndServeTLS("localhost:1965", "localhost.crt", "localhost.key"))
// }
//
// You can also checkout cmd/main.go as an example.
//
// Make sure to generate your cert for localhost:
//
// openssl req \
// -x509 \
// -out localhost.crt \
// -keyout localhost.key \
// -newkey rsa:2048 \
// -nodes \
// -sha256 \
// -subj '/CN=localhost' \
// -extensions EXT \
// -config <( printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")
//
package gemini
import (
"os"
"strings"
)
var srv = &Server{}
type HandlerFunc func(*Response, *Request)
func (f HandlerFunc) ServeGemini(w *Response, r *Request) {
f(w, r)
}
type handledPath struct {
handler Handler
p string
}
type basicHandler struct {
handlers []handledPath
}
func (b *basicHandler) ServeGemini(w *Response, r *Request) {
u := r.URL.Path
if u == "" {
u = "/"
}
for _, h := range b.handlers {
if strings.HasPrefix(u, h.p) {
h.handler.ServeGemini(w, r)
return
}
}
w.SetStatus(StatusNotFound, u+" Not Found!")
}
var basic = &basicHandler{}
func Handle(p string, h Handler) {
basic.handlers = append(basic.handlers, handledPath{handler: h, p: p})
}
func HandleFunc(p string, f HandlerFunc) {
basic.handlers = append(basic.handlers, handledPath{handler: f, p: p})
}
func ListenAndServeTLS(addr string, certFile, keyFile string) error {
s := Server{Addr: addr, Handler: basic, Log: os.Stdout}
return s.ListenAndServeTLS(certFile, keyFile)
}