init
This commit is contained in:
commit
ca4bd7d7c7
10 changed files with 944 additions and 0 deletions
146
internal/server/server.go
Normal file
146
internal/server/server.go
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/wzray/dns/internal/resolv"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
mgr *resolv.Manager
|
||||
log *slog.Logger
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
func New(mgr *resolv.Manager, log *slog.Logger) *Server {
|
||||
s := &Server{mgr: mgr, log: log, mux: http.NewServeMux()}
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.withLogging(s.mux)
|
||||
}
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.mux.HandleFunc("GET /health", s.handleHealth)
|
||||
s.mux.HandleFunc("GET /dns", s.handleList)
|
||||
s.mux.HandleFunc("POST /dns", s.handleAdd)
|
||||
s.mux.HandleFunc("DELETE /dns/{address}", s.handleRemove)
|
||||
}
|
||||
|
||||
type listResponse struct {
|
||||
Servers []string `json:"servers"`
|
||||
}
|
||||
|
||||
type addRequest struct {
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleList(w http.ResponseWriter, r *http.Request) {
|
||||
servers, err := s.mgr.List()
|
||||
if err != nil {
|
||||
s.log.Error("list nameservers", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to read nameservers")
|
||||
return
|
||||
}
|
||||
if servers == nil {
|
||||
servers = []string{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, listResponse{Servers: servers})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdd(w http.ResponseWriter, r *http.Request) {
|
||||
var req addRequest
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
if req.Address == "" {
|
||||
writeError(w, http.StatusBadRequest, "address is required")
|
||||
return
|
||||
}
|
||||
|
||||
err := s.mgr.Add(req.Address)
|
||||
switch {
|
||||
case err == nil:
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"address": req.Address})
|
||||
case errors.Is(err, resolv.ErrInvalidAddress):
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
case errors.Is(err, resolv.ErrAlreadyExists):
|
||||
writeError(w, http.StatusConflict, err.Error())
|
||||
default:
|
||||
s.log.Error("add nameserver", "addr", req.Address, "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to add nameserver")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleRemove(w http.ResponseWriter, r *http.Request) {
|
||||
addr := r.PathValue("address")
|
||||
if addr == "" {
|
||||
writeError(w, http.StatusBadRequest, "address is required")
|
||||
return
|
||||
}
|
||||
|
||||
err := s.mgr.Remove(addr)
|
||||
switch {
|
||||
case err == nil:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case errors.Is(err, resolv.ErrInvalidAddress):
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
case errors.Is(err, resolv.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, err.Error())
|
||||
default:
|
||||
s.log.Error("remove nameserver", "addr", addr, "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to remove nameserver")
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, errorResponse{Error: msg})
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *Server) withLogging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
s.log.Info("http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"remote", r.RemoteAddr,
|
||||
)
|
||||
})
|
||||
}
|
||||
103
internal/server/server_test.go
Normal file
103
internal/server/server_test.go
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/wzray/dns/internal/resolv"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
mgr := resolv.New(path)
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return New(mgr, log), path
|
||||
}
|
||||
|
||||
func do(t *testing.T, h http.Handler, method, target string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
rdr = bytes.NewReader(b)
|
||||
}
|
||||
req := httptest.NewRequest(method, target, rdr)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestServer_AddListRemove(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
h := s.Handler()
|
||||
|
||||
rec := do(t, h, "GET", "/dns", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("list: status %d", rec.Code)
|
||||
}
|
||||
var lr listResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &lr); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(lr.Servers) != 0 {
|
||||
t.Fatalf("want empty, got %v", lr.Servers)
|
||||
}
|
||||
|
||||
rec = do(t, h, "POST", "/dns", addRequest{Address: "1.1.1.1"})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("add: status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
rec = do(t, h, "POST", "/dns", addRequest{Address: "1.1.1.1"})
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("dup: status %d", rec.Code)
|
||||
}
|
||||
|
||||
rec = do(t, h, "POST", "/dns", addRequest{Address: "not-an-ip"})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid: status %d", rec.Code)
|
||||
}
|
||||
|
||||
rec = do(t, h, "DELETE", "/dns/1.1.1.1", nil)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("remove: status %d", rec.Code)
|
||||
}
|
||||
|
||||
rec = do(t, h, "DELETE", "/dns/1.1.1.1", nil)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("remove missing: status %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_BadJSON(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
h := s.Handler()
|
||||
req := httptest.NewRequest("POST", "/dns", bytes.NewReader([]byte("{not json")))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_HealthAndUnknownRoute(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
h := s.Handler()
|
||||
|
||||
if rec := do(t, h, "GET", "/health", nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("health status %d", rec.Code)
|
||||
}
|
||||
if rec := do(t, h, "GET", "/unknown", nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown route status %d", rec.Code)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue