Compare commits
4 Commits
setup-and-
...
cleanup
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e30da54e2 | ||
|
|
f67d57fedf | ||
|
|
700b7ad457 | ||
|
|
749d544165 |
12
Makefile
12
Makefile
@@ -1,9 +1,9 @@
|
|||||||
.PHONY: *
|
.PHONY: *
|
||||||
|
|
||||||
help: ## This help dialog.
|
help:
|
||||||
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2 | "sort -u"}' $(MAKEFILE_LIST)
|
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2 | "sort -u"}' $(MAKEFILE_LIST)
|
||||||
|
|
||||||
check-docker: ## Verify Docker CLI is available
|
check-docker: ## Verify Docker CLI available
|
||||||
@command -v docker >/dev/null 2>&1 || { \
|
@command -v docker >/dev/null 2>&1 || { \
|
||||||
echo "Error: docker not found."; \
|
echo "Error: docker not found."; \
|
||||||
echo "Install Docker Desktop: https://docs.docker.com/desktop/setup/install/mac-install/"; \
|
echo "Install Docker Desktop: https://docs.docker.com/desktop/setup/install/mac-install/"; \
|
||||||
@@ -17,20 +17,20 @@ run: check-docker ## Start the application with Docker Compose
|
|||||||
run-local: ## Start the application locally (without Docker)
|
run-local: ## Start the application locally (without Docker)
|
||||||
go run ./cmd/app
|
go run ./cmd/app
|
||||||
|
|
||||||
down: check-docker ## Stop the application
|
down: check-docker
|
||||||
docker compose down --remove-orphans
|
docker compose down --remove-orphans
|
||||||
|
|
||||||
setup-local: copy-config install-dependencies ## Install config and Go dependencies
|
setup-local: copy-config install-dependencies ## Install config and Go dependencies
|
||||||
|
|
||||||
setup-docker: setup-local run ## Install dependencies and start with Docker Compose
|
setup-docker: setup-local run ## Install dependencies and start with Docker Compose
|
||||||
|
|
||||||
install-lint: ## Install Go lint
|
install-lint:
|
||||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
||||||
|
|
||||||
install-dependencies: ## Install Go project dependencies
|
install-dependencies: ## Install Go project dependencies
|
||||||
go mod download
|
go mod download
|
||||||
|
|
||||||
copy-config: ## Copy config file if missing
|
copy-config:
|
||||||
@test -f .env || cp .env.dist .env
|
@test -f .env || cp .env.dist .env
|
||||||
|
|
||||||
lint: install-lint ## Run lint
|
lint: install-lint ## Run lint
|
||||||
@@ -39,5 +39,7 @@ lint: install-lint ## Run lint
|
|||||||
tests: ## Run tests
|
tests: ## Run tests
|
||||||
go test -v ./...
|
go test -v ./...
|
||||||
|
|
||||||
|
validation: lint tests ## Run lint and tests
|
||||||
|
|
||||||
build: ## Build the server binary
|
build: ## Build the server binary
|
||||||
go build -o bin/server ./cmd/app
|
go build -o bin/server ./cmd/app
|
||||||
|
|||||||
BIN
bin/server
BIN
bin/server
Binary file not shown.
@@ -1,4 +1,4 @@
|
|||||||
package httpjson
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -31,16 +31,6 @@ func New(logger *zap.Logger) (*echo.Echo, Handler) {
|
|||||||
|
|
||||||
// RunServer runs http server and listens until context is canceled.
|
// RunServer runs http server and listens until context is canceled.
|
||||||
func (h *Handler) RunServer(ctx context.Context, conf *config.Config, e *echo.Echo) error {
|
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{
|
server := &http.Server{
|
||||||
Addr: fmt.Sprintf(":%d", conf.API.Port),
|
Addr: fmt.Sprintf(":%d", conf.API.Port),
|
||||||
ReadTimeout: time.Duration(conf.API.ReadTimeout) * time.Second,
|
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,
|
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")
|
return errors.Wrap(err, "server error")
|
||||||
}
|
}
|
||||||
|
|
||||||
87
cmd/app/handler/handler_test.go
Normal file
87
cmd/app/handler/handler_test.go
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package httpjson
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
35
cmd/app/handler/health_test.go
Normal file
35
cmd/app/handler/health_test.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/kjannette/go_http_server/cmd/app/handler/httpjson"
|
"github.com/kjannette/go_http_server/cmd/app/handler"
|
||||||
"github.com/kjannette/go_http_server/internal/config"
|
"github.com/kjannette/go_http_server/internal/config"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@@ -14,7 +14,7 @@ func run(ctx context.Context, cfg *config.Config) error {
|
|||||||
lg := zap.L().With(zap.String("app_name", appName), zap.String("app_version", appVersion))
|
lg := zap.L().With(zap.String("app_name", appName), zap.String("app_version", appVersion))
|
||||||
|
|
||||||
eg, ctx := errgroup.WithContext(ctx)
|
eg, ctx := errgroup.WithContext(ctx)
|
||||||
app, h := httpjson.New(lg)
|
app, h := handler.New(lg)
|
||||||
serverLog := lg.Named("run_server")
|
serverLog := lg.Named("run_server")
|
||||||
|
|
||||||
eg.Go(func() error {
|
eg.Go(func() error {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config represents the application configuration.
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
API struct {
|
API struct {
|
||||||
Port int `envconfig:"API_PORT" default:"3000"`
|
Port int `envconfig:"API_PORT" default:"3000"`
|
||||||
@@ -16,7 +15,6 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewConfig creates a new initialised application Config.
|
|
||||||
func NewConfig() (*Config, error) {
|
func NewConfig() (*Config, error) {
|
||||||
var config Config
|
var config Config
|
||||||
|
|
||||||
|
|||||||
91
internal/config/config_test.go
Normal file
91
internal/config/config_test.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var configEnvKeys = []string{
|
||||||
|
"API_PORT",
|
||||||
|
"API_READ_TIMEOUT",
|
||||||
|
"API_WRITE_TIMEOUT",
|
||||||
|
"API_IDLE_TIMEOUT",
|
||||||
|
"API_TIMEOUT",
|
||||||
|
"API_API_PORT",
|
||||||
|
"API_API_READ_TIMEOUT",
|
||||||
|
"API_API_WRITE_TIMEOUT",
|
||||||
|
"API_API_IDLE_TIMEOUT",
|
||||||
|
"API_API_TIMEOUT",
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearConfigEnv(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
for _, key := range configEnvKeys {
|
||||||
|
key := key
|
||||||
|
if prev, ok := os.LookupEnv(key); ok {
|
||||||
|
prev := prev
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = os.Setenv(key, prev)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewConfig_Defaults(t *testing.T) {
|
||||||
|
clearConfigEnv(t)
|
||||||
|
|
||||||
|
cfg, err := NewConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.API.Port != 3000 {
|
||||||
|
t.Errorf("API.Port = %d, want 3000", cfg.API.Port)
|
||||||
|
}
|
||||||
|
if cfg.API.ReadTimeout != 7 {
|
||||||
|
t.Errorf("API.ReadTimeout = %d, want 7", cfg.API.ReadTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.WriteTimeout != 5 {
|
||||||
|
t.Errorf("API.WriteTimeout = %d, want 5", cfg.API.WriteTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.IdleTimeout != 5 {
|
||||||
|
t.Errorf("API.IdleTimeout = %d, want 5", cfg.API.IdleTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.Timeout != 5 {
|
||||||
|
t.Errorf("API.Timeout = %d, want 5", cfg.API.Timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewConfig_FromEnv(t *testing.T) {
|
||||||
|
t.Setenv("API_PORT", "9090")
|
||||||
|
t.Setenv("API_READ_TIMEOUT", "10")
|
||||||
|
t.Setenv("API_WRITE_TIMEOUT", "11")
|
||||||
|
t.Setenv("API_IDLE_TIMEOUT", "12")
|
||||||
|
t.Setenv("API_TIMEOUT", "13")
|
||||||
|
|
||||||
|
cfg, err := NewConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.API.Port != 9090 {
|
||||||
|
t.Errorf("API.Port = %d, want 9090", cfg.API.Port)
|
||||||
|
}
|
||||||
|
if cfg.API.ReadTimeout != 10 {
|
||||||
|
t.Errorf("API.ReadTimeout = %d, want 10", cfg.API.ReadTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.WriteTimeout != 11 {
|
||||||
|
t.Errorf("API.WriteTimeout = %d, want 11", cfg.API.WriteTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.IdleTimeout != 12 {
|
||||||
|
t.Errorf("API.IdleTimeout = %d, want 12", cfg.API.IdleTimeout)
|
||||||
|
}
|
||||||
|
if cfg.API.Timeout != 13 {
|
||||||
|
t.Errorf("API.Timeout = %d, want 13", cfg.API.Timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
38
internal/infrastructure/os/signal_test.go
Normal file
38
internal/infrastructure/os/signal_test.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package os
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSignalListener_CancelsOnSIGTERM(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
canceled := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
close(canceled)
|
||||||
|
}()
|
||||||
|
|
||||||
|
SignalListener(zap.NewNop(), cancel)
|
||||||
|
|
||||||
|
proc, err := os.FindProcess(os.Getpid())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("FindProcess: %v", err)
|
||||||
|
}
|
||||||
|
if err := proc.Signal(syscall.SIGTERM); err != nil {
|
||||||
|
t.Fatalf("Signal SIGTERM: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-canceled:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("context was not canceled after SIGTERM")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"go.uber.org/zap/zapcore"
|
"go.uber.org/zap/zapcore"
|
||||||
)
|
)
|
||||||
|
|
||||||
// init initializes zap's global loggers (i.e. zap.L() and zap.S()).
|
|
||||||
// Log level is retrieved from environment variable LOG_LEVEL, defaulting to "info" otherwise.
|
// Log level is retrieved from environment variable LOG_LEVEL, defaulting to "info" otherwise.
|
||||||
// To activate this facility, add a blank import to this package.
|
// To activate this facility, add a blank import to this package.
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
27
pkg/logger/logger_test.go
Normal file
27
pkg/logger/logger_test.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package logger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInitializeZapGlobals_InfoLevel(t *testing.T) {
|
||||||
|
initializeZapGlobals("info")
|
||||||
|
|
||||||
|
if zap.L().Core().Enabled(zapcore.DebugLevel) {
|
||||||
|
t.Error("debug level should be disabled when LOG_LEVEL is info")
|
||||||
|
}
|
||||||
|
if !zap.L().Core().Enabled(zapcore.InfoLevel) {
|
||||||
|
t.Error("info level should be enabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInitializeZapGlobals_DebugLevel(t *testing.T) {
|
||||||
|
initializeZapGlobals("debug")
|
||||||
|
|
||||||
|
if !zap.L().Core().Enabled(zapcore.DebugLevel) {
|
||||||
|
t.Error("debug level should be enabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user