Repository navigation
Expand file tree
/
Copy pathcontroller.go
More file actions
82 lines (60 loc) · 1.5 KB
/
Copy pathcontroller.go
File metadata and controls
82 lines (60 loc) · 1.5 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
package cantainer
import (
"context"
"encoding/json"
"log"
"net/http"
"net/netip"
"time"
)
type HTTP struct {
server *http.Server
core *core
}
func NewHTTP(core *core) *HTTP {
mux := http.NewServeMux()
server := http.Server{
Addr: ":20043",
Handler: mux,
}
controller := HTTP{
server: &server,
core: core,
}
mux.HandleFunc("POST /register", controller.NetworkIP)
return &controller
}
func (h *HTTP) Run(ctx context.Context) error {
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := h.server.Shutdown(shutdownCtx); err != nil {
log.Fatal(err)
}
}()
return h.server.ListenAndServe()
}
type RegisterContainerHTTPRequest struct {
Network netip.Prefix `json:"network"`
}
type RegisterContainerHTTPResponse struct {
Address netip.Addr `json:"address"`
}
func (h *HTTP) NetworkIP(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var request RegisterContainerHTTPRequest
if err := dec.Decode(&request); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
addr, err := h.core.RegisterContainer(context.Background(), &request.Network)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(RegisterContainerHTTPResponse{Address: addr}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}