this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

refactor(api): separate struct for API

For future shared mutable state.

Khue Doan e30a5b14 59e2b4ef

+37 -13
+1 -2
cmd/nixie/main.go
··· 72 72 log.Info("PXE server started", "address", address) 73 73 74 74 go func() { 75 - if err := serve.StartAPIServer(ctx, flags.Debug); err != nil { 75 + if err := serve.StartAPIServer(ctx, hostsConfig, flags.Debug); err != nil { 76 76 log.Fatal("failed to start API server", "error", err) 77 77 } 78 78 }() 79 - log.Info("API server started", "address", address) 80 79 81 80 // TODO IMPORTANT obviously, should be API call 82 81 // TODO IMPORTANT support SSH key
+36 -11
internal/serve/api.go
··· 6 6 "net" 7 7 "net/http" 8 8 9 + "code.khuedoan.com/nixie/internal/hosts" 9 10 "github.com/charmbracelet/log" 10 11 ) 11 12 13 + type API struct { 14 + hostsConfig hosts.HostsConfig 15 + } 16 + 17 + func (api *API) ping(w http.ResponseWriter, r *http.Request) { 18 + log.Info("received ping from agent", "ip", extractClientIP(r)) 19 + io.WriteString(w, "pong") 20 + } 21 + 22 + func (api *API) router() http.Handler { 23 + mux := http.NewServeMux() 24 + mux.HandleFunc("GET /ping", api.ping) 25 + 26 + return mux 27 + } 28 + 29 + func StartAPIServer(ctx context.Context, hostsConfig hosts.HostsConfig, debug bool) error { 30 + api := &API{ 31 + hostsConfig: hostsConfig, 32 + } 33 + 34 + server := &http.Server{ 35 + Addr: ":5000", 36 + Handler: api.router(), 37 + } 38 + log.Info("starting API server", "address", server.Addr) 39 + 40 + go func() { 41 + <-ctx.Done() 42 + server.Shutdown(ctx) 43 + }() 44 + 45 + return server.ListenAndServe() 46 + } 47 + 12 48 func extractClientIP(r *http.Request) string { 13 49 ip, _, err := net.SplitHostPort(r.RemoteAddr) 14 50 if err != nil { ··· 17 53 18 54 return ip 19 55 } 20 - 21 - func handlePing(w http.ResponseWriter, r *http.Request) { 22 - log.Info("received ping from agent", "ip", extractClientIP(r)) 23 - io.WriteString(w, "pong") 24 - } 25 - 26 - func StartAPIServer(ctx context.Context, debug bool) error { 27 - http.HandleFunc("GET /ping", handlePing) 28 - 29 - return http.ListenAndServe(":5000", nil) 30 - }