-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhttp.go
174 lines (156 loc) · 4.68 KB
/
http.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package main
import (
"encoding/json"
"errors"
"html/template"
"io"
"net/http"
)
type HTTPServer struct {
store Store
tunnelManager *TunnelManager
chatCrawlerDetector *ChatCrawlerDetector
}
func NewHTTPServer(
store Store,
tunnelManager *TunnelManager,
chatCrawlerDetector *ChatCrawlerDetector,
) *HTTPServer {
return &HTTPServer{
store: store,
tunnelManager: tunnelManager,
chatCrawlerDetector: chatCrawlerDetector,
}
}
func (h *HTTPServer) handleHomePage(w http.ResponseWriter, r *http.Request) {
logger := GetLogger()
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
return
}
t, err := template.New("index.html").ParseFiles("./templates/index.html")
if err != nil {
logger.Error("failed to parse template", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
key, err := h.store.Get(r.Context(), CodeUploadedCountKey)
switch {
case errors.Is(err, ErrKeyNotFound):
key = []byte("0")
case err != nil:
logger.Error("failed to get key", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
err = t.Execute(w, string(key))
if err != nil {
logger.Error("failed to execute template", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
}
func (h *HTTPServer) handleCodePage(w http.ResponseWriter, r *http.Request) {
logger := GetLogger()
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
return
}
key := r.URL.Path[3:]
code, err := h.store.Get(r.Context(), key)
switch {
case errors.Is(err, ErrKeyNotFound):
logger.Info("key not found", "key", key)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
return
case err != nil:
logger.Error("failed to get key from redis", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
logger.Debug("fetched code from store", "key", key, "code", string(code))
t, err := template.New("code.html").ParseFiles("./templates/code.html")
if err != nil {
logger.Error("failed to parse template", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
err = t.Execute(w, string(code))
if err != nil {
logger.Error("failed to execute template", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
}
func (h *HTTPServer) handleTunnel(w http.ResponseWriter, r *http.Request) {
logger := GetLogger()
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
return
}
if h.chatCrawlerDetector.IsChatCrawler(r.Header.Get("User-Agent")) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 - Forbidden"))
return
}
key := r.URL.Path[3:]
tunnel := h.tunnelManager.GetTunnel(key)
if tunnel == nil {
logger.Info("key not found", "key", key)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
return
}
defer tunnel.Done()
logger.Debug("fetched tunnel from store", "key", key)
n, err := io.Copy(w, tunnel)
switch {
case errors.Is(err, ErrStreamSizeExceeded):
logger.Warn("stream size exceeded", "key", key)
return
case err != nil:
logger.Error("failed to copy from tunnel to http response", "error", err)
return
}
logger.Debug("copied bytes from tunnel to http response", "key", key, "bytes", n)
}
func (h *HTTPServer) getTunnelCount(w http.ResponseWriter, r *http.Request) {
logger := GetLogger()
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
return
}
type tunnelCount struct {
TunnelCount int `json:"tunnelCount"`
}
w.Header().Set("Content-Type", "application/json")
tc := tunnelCount{h.tunnelManager.TunnelCount()}
err := json.NewEncoder(w).Encode(tc)
if err != nil {
logger.Error("failed to encode tunnel count", "error", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
return
}
}
func (h *HTTPServer) ListenAndServe(addr string) error {
mux := http.NewServeMux()
mux.HandleFunc("/", h.handleHomePage)
mux.HandleFunc("/c/", h.handleCodePage)
mux.HandleFunc("/t/", h.handleTunnel)
mux.HandleFunc("/tunnels", h.getTunnelCount)
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
return http.ListenAndServe(addr, mux)
}