-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathserver.go
More file actions
99 lines (89 loc) · 2.06 KB
/
server.go
File metadata and controls
99 lines (89 loc) · 2.06 KB
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
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"time"
"github.com/stackrox/rox/pkg/sync"
)
type message struct {
Headers map[string][]string `json:"headers"`
Data map[string]interface{} `json:"data"`
}
var (
lock sync.Mutex
dataPosted []message
)
func postHandler(w http.ResponseWriter, r *http.Request) {
defer func() {
_ = r.Body.Close()
}()
data, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Failed to read body: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
dataMap := make(map[string]interface{})
if err := json.Unmarshal(data, &dataMap); err != nil {
log.Printf("Error unmarshalling data: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
lock.Lock()
defer lock.Unlock()
dataPosted = append(dataPosted, message{Headers: r.Header, Data: dataMap})
w.WriteHeader(http.StatusOK)
}
func getHandler(w http.ResponseWriter, _ *http.Request) {
lock.Lock()
defer lock.Unlock()
resp, err := json.Marshal(&dataPosted)
if err != nil {
log.Printf("Failed to marshal resp: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if _, err := w.Write(resp); err != nil {
log.Printf("Failed to write resp: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getHandler(w, r)
case http.MethodPost:
postHandler(w, r)
default:
w.WriteHeader(http.StatusBadRequest)
}
}
func tlsServer() {
server := &http.Server{
ReadHeaderTimeout: 5 * time.Second,
Addr: ":8443",
Handler: http.HandlerFunc(rootHandler),
}
err := server.ListenAndServeTLS("/tmp/certs/server.crt", "/tmp/certs/server.key")
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func nonTLSServer() {
server := &http.Server{
ReadHeaderTimeout: 5 * time.Second,
Addr: ":8080",
Handler: http.HandlerFunc(rootHandler),
}
if err := server.ListenAndServe(); err != nil {
panic(err)
}
}
func main() {
go tlsServer()
go nonTLSServer()
select {}
}