added test files

This commit is contained in:
KS Jannette
2026-05-19 03:49:03 -04:00
parent 749d544165
commit 700b7ad457
7 changed files with 292 additions and 11 deletions

View File

@@ -31,16 +31,6 @@ func New(logger *zap.Logger) (*echo.Echo, Handler) {
// RunServer runs http server and listens until context is canceled.
func (h *Handler) RunServer(ctx context.Context, conf *config.Config, e *echo.Echo) error {
go func() {
<-ctx.Done()
timeout, cancel := context.WithTimeout(context.Background(), time.Duration(conf.API.ReadTimeout)*time.Second)
defer cancel()
_ = e.Shutdown(timeout) // try gracefully first
_ = e.Close() // immediate termination
}()
server := &http.Server{
Addr: fmt.Sprintf(":%d", conf.API.Port),
ReadTimeout: time.Duration(conf.API.ReadTimeout) * time.Second,
@@ -48,7 +38,18 @@ func (h *Handler) RunServer(ctx context.Context, conf *config.Config, e *echo.Ec
IdleTimeout: time.Duration(conf.API.IdleTimeout) * time.Second,
}
if err := e.StartServer(server); !errors.Is(err, http.ErrServerClosed) {
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Duration(conf.API.ReadTimeout)*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
h.logger.Warn("graceful shutdown failed", zap.Error(err))
}
}()
if err := e.StartServer(server); err != nil && !errors.Is(err, http.ErrServerClosed) {
return errors.Wrap(err, "server error")
}

View File

@@ -0,0 +1,87 @@
package httpjson
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"time"
"github.com/kjannette/go_http_server/internal/config"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
func TestRunServer_ShutdownOnCancel(t *testing.T) {
e, h := New(zap.NewNop())
cfg := &config.Config{}
cfg.API.Port = 0
cfg.API.ReadTimeout = 2
cfg.API.WriteTimeout = 2
cfg.API.IdleTimeout = 2
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error, 1)
go func() {
errCh <- h.RunServer(ctx, cfg, e)
}()
healthURL, err := waitForHealthURL(e, 3*time.Second)
if err != nil {
t.Fatal(err)
}
client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
resp, err := client.Get(healthURL)
if err != nil {
t.Fatalf("GET /health: %v", err)
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
t.Fatalf("read body: %v", err)
}
if resp.StatusCode != http.StatusOK || string(body) != "OK" {
t.Fatalf("health check: status=%d body=%q", resp.StatusCode, body)
}
cancel()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("RunServer() error = %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("RunServer did not exit after context cancel")
}
}
func waitForHealthURL(e *echo.Echo, timeout time.Duration) (string, error) {
client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if e.Listener != nil {
_, port, err := net.SplitHostPort(e.Listener.Addr().String())
if err != nil {
return "", fmt.Errorf("split listener addr: %w", err)
}
url := fmt.Sprintf("http://127.0.0.1:%s/health", port)
resp, err := client.Get(url)
if err == nil {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return url, nil
}
}
}
time.Sleep(10 * time.Millisecond)
}
return "", fmt.Errorf("server not ready within %s", timeout)
}

View File

@@ -0,0 +1,35 @@
package httpjson
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"go.uber.org/zap"
)
func TestHealthCheck(t *testing.T) {
e, _ := New(zap.NewNop())
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
}
body, err := io.ReadAll(rec.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if string(body) != "OK" {
t.Errorf("body = %q, want %q", body, "OK")
}
if ct := rec.Header().Get("Content-Type"); ct != "text/plain; charset=UTF-8" {
t.Errorf("Content-Type = %q, want text/plain; charset=UTF-8", ct)
}
}