-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
98 lines (72 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
package main
import (
"bufio"
"encoding/json"
"github.com/emirpasic/gods/sets/hashset"
"log"
"net/http"
"os"
)
// Library functions
// Error handling for file IO
func check(e error) {
if e != nil {
panic(e)
}
}
// Endpoints
type PingResponse struct {
Response string `json:"response"`
}
func Ping(w http.ResponseWriter, req *http.Request) {
result := PingResponse{ Response: "PONG" }
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encodeErr := encoder.Encode(&result)
check(encodeErr)
}
// Pass around the 100K set
type HundredK struct {
set *hashset.Set
}
type Check100kRequest struct {
Value string `json:"value"`
}
type Check100kResponse struct {
Common bool `json:"common"`
}
// Process request to check 100k list
func (hundredK *HundredK) Check100kServer(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var body Check100kRequest
decodeErr := decoder.Decode(&body)
check(decodeErr)
result := Check100kResponse{ Common: hundredK.set.Contains(body.Value) }
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encodeErr := encoder.Encode(&result)
check(encodeErr)
}
// Server
func main() {
log.Print("Loading resources...")
hundredKFile, err := os.Open("ncsc-common-100k.txt")
check(err)
fileScanner := bufio.NewScanner(hundredKFile)
fileScanner.Split(bufio.ScanLines)
hundredKSet := hashset.New()
for fileScanner.Scan() {
hundredKSet.Add(fileScanner.Text())
}
hundredKFile.Close()
hundredK := &HundredK{set: hundredKSet}
log.Print("Resources Loaded.")
// TODO: Check file existence and output nice error message
log.Print("Riddler Server is listening...")
http.HandleFunc("/ping", Ping)
http.HandleFunc("/check-100k", hundredK.Check100kServer)
listenErr := http.ListenAndServeTLS(":8080", "server.crt", "server.key", nil)
if listenErr != nil {
log.Fatal("ListenAndServe: ", err)
}
}