-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (64 loc) · 1.53 KB
/
main.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
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"unicode/utf8"
)
var config = LoadConfig("config.json")
var serverList = NewServerList(config)
func main() {
http.HandleFunc("/list", listHandler)
http.HandleFunc("/publish", publishHandler)
log.Fatal(http.ListenAndServe(config.ListenAddress, nil))
}
func listHandler(rw http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
badRequest(rw)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.Write(serverList.List())
}
func publishHandler(rw http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badRequest(rw)
return
}
host := ""
port := req.Header.Get("Fb-Port")
if config.BeingProxied {
host = req.Header.Get(config.RealIPHeader)
} else {
host, _, _ = net.SplitHostPort(req.RemoteAddr)
}
if port == "" {
badRequest(rw)
return
}
payload, err := ioutil.ReadAll(req.Body)
if err != nil {
internalError(rw, err)
return
} else if len(payload) > config.MaxPayloadSize {
badRequest(rw)
return
}
if !utf8.Valid(payload) {
payload = []byte(base64.StdEncoding.EncodeToString(payload))
}
err = serverList.Publish(net.JoinHostPort(host, port), payload)
if err != nil {
internalError(rw, err)
}
rw.Header().Set("Fb-Expire", fmt.Sprint(config.ExpireTime))
}
func badRequest(rw http.ResponseWriter) {
http.Error(rw, "400 bad request", http.StatusBadRequest)
}
func internalError(rw http.ResponseWriter, err error) {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}