-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
117 lines (91 loc) · 2.06 KB
/
server.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
114
115
116
117
package gemini
import (
"bytes"
"crypto/tls"
"errors"
"log"
"net"
"net/url"
)
type Server struct {
Addr string
Handler Handler
//ServeMux *ServeMux
ListenerAcceptErrorHandler func(error)
//tlsConfig *tls.Config
listener net.Listener
stop chan struct{}
newConn chan net.Conn
}
func NewServer() *Server {
server := &Server{
Handler: new(ServeMux)}
return server
}
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = defaultListenAddress
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{cert}}
srv.listener, err = tls.Listen("tcp", addr, tlsConfig)
if err != nil {
return err
}
srv.stop = make(chan struct{})
srv.newConn = make(chan net.Conn)
for {
rw, err := srv.listener.Accept()
if err != nil {
if srv.ListenerAcceptErrorHandler != nil {
srv.ListenerAcceptErrorHandler(err)
}
break
}
go srv.serve(rw)
}
return nil
}
func (srv *Server) serve(rw net.Conn) {
defer rw.Close()
requestBytes := make([]byte, 1024)
n, err := rw.Read(requestBytes)
if err != nil {
log.Println(err)
return
}
requestBytes = requestBytes[:n]
newLinePos := bytes.Index(requestBytes, newLine)
if newLinePos == -1 {
if srv.ListenerAcceptErrorHandler != nil {
srv.ListenerAcceptErrorHandler(errors.New("request does not ends with \\r\\n"))
}
return
}
requestBytes = requestBytes[:newLinePos]
requestUrl, err := url.Parse(string(requestBytes))
if err != nil {
log.Println(err)
return
}
query, _ := url.PathUnescape(requestUrl.RawQuery)
request := &Request{
URL: requestUrl,
Host: requestUrl.Host,
RequestURI: requestUrl.Path,
RemoteAddr: rw.RemoteAddr().String(),
Query: query}
response := &response{
rw: rw,
header: new(Header)}
response.header.Status = StatusSuccess
response.header.Meta = "text/gemini"
serverHandler{srv}.ServeGemini(response, request)
}
func (server *Server) Stop() error {
return server.listener.Close()
}