p0: skeleton, dialer-Control URL guard, flake, Makefile
Go service with /healthz, SSRF guard (parse + resolve-all + Control), exhaustive tests, NixOS module, and Makefile as source of truth for build flags. nix flake check runs make test lint.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Version is set from main via New.
|
||||
type Server struct {
|
||||
Version string
|
||||
Mux *http.ServeMux
|
||||
}
|
||||
|
||||
func New(version string) *Server {
|
||||
s := &Server{Version: version, Mux: http.NewServeMux()}
|
||||
s.Mux.HandleFunc("GET /healthz", s.healthz)
|
||||
s.Mux.HandleFunc("GET /healthz/", s.healthz)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"status": "ok",
|
||||
"version": s.Version,
|
||||
})
|
||||
}
|
||||
|
||||
// HTTPServer wraps the mux with timeouts. Listen address is the caller's.
|
||||
func (s *Server) HTTPServer(addr string) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
Handler: s.Mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHealthz(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := New("testver")
|
||||
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
s.Mux.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status %d", rec.Code)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["status"] != "ok" {
|
||||
t.Fatalf("status=%v", body["status"])
|
||||
}
|
||||
if body["version"] != "testver" {
|
||||
t.Fatalf("version=%v", body["version"])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user