Skip to content

Commit 52fcc83

Browse files
committed
Make common function for writing static responses
1 parent d1ab3ce commit 52fcc83

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

ipieces/ipieces.go

+12-12
Original file line numberDiff line numberDiff line change
@@ -193,36 +193,36 @@ func (d *data) flip() {
193193
}
194194
}
195195

196+
func writeResponse(w http.ResponseWriter, code int, body string, format string, args ...any) {
197+
fmt.Printf(format, args...)
198+
w.WriteHeader(code)
199+
if _, err := io.WriteString(w, body); err != nil {
200+
fmt.Println("WriteString failed:", err)
201+
}
202+
}
203+
196204
func (p Puzzle) handle(w http.ResponseWriter, req *http.Request, tmpl *template.Template) {
197205
d, err := p.dataFromReq(req)
198206
fmt.Printf("IP %s index %d\n", d.IP, d.Index)
199207
if err != nil {
200-
fmt.Println("dataFromReq failed:", err)
201-
w.WriteHeader(http.StatusInternalServerError)
202-
io.WriteString(w, errorPage)
208+
writeResponse(w, http.StatusInternalServerError, errorPage, "dataFromReq failed: %v", err)
203209
return
204210
}
205211

206212
if p.Client != nil {
207213
resp, err := p.Client.Query(d.IP)
208214
if err != nil {
209215
if err == vpnapi.ErrRateLimited {
210-
fmt.Println("rate limited:", err)
211-
w.WriteHeader(http.StatusInternalServerError)
212-
io.WriteString(w, rateLimitPage)
216+
writeResponse(w, http.StatusTooManyRequests, rateLimitPage, "rate limited: %v", err)
213217
return
214218
}
215219
// TODO: This fails closed. This may be too strict, especially if vpnapi.io is unreliable.
216-
fmt.Println("Query failed:", err)
217-
w.WriteHeader(http.StatusInternalServerError)
218-
io.WriteString(w, errorPage)
220+
writeResponse(w, http.StatusInternalServerError, errorPage, "Query failed: %v", err)
219221
return
220222
}
221223

222224
if resp.Security.VPN || resp.Security.Proxy || resp.Security.Tor || resp.Security.Relay {
223-
fmt.Printf("%t %t %t %t\n", resp.Security.VPN, resp.Security.Proxy, resp.Security.Tor, resp.Security.Relay)
224-
w.WriteHeader(http.StatusForbidden)
225-
io.WriteString(w, vpnPage)
225+
writeResponse(w, http.StatusForbidden, vpnPage, "%t %t %t %t\n", resp.Security.VPN, resp.Security.Proxy, resp.Security.Tor, resp.Security.Relay)
226226
return
227227
}
228228
}

0 commit comments

Comments
 (0)