A simple and opinionated HTTP server package for Go that provides easy server creation, graceful shutdown, and JSON response helpers.
- Simple Server Creation: Create HTTP servers with route patterns and handlers
- TLS Support: Built-in TLS/HTTPS support
- Graceful Shutdown: Handles context cancellation and OS signals (SIGINT, SIGTERM)
- JSON Helpers: Convenient function for writing JSON responses
- Error Handling: Proper error handling and logging
go get github.com/ducksify/httpserverpackage main
import (
"context"
"net/http"
"github.com/ducksify/httpserver"
)
func main() {
// Define handlers
helloHandler := func(w http.ResponseWriter, r *http.Request) {
httpserver.WriteJSON(w, http.StatusOK, map[string]string{
"message": "Hello, World!",
})
}
healthHandler := func(w http.ResponseWriter, r *http.Request) {
httpserver.WriteJSON(w, http.StatusOK, map[string]string{
"status": "ok",
})
}
// Create server with routes
patterns := []string{"/hello", "/health"}
handlers := []http.HandlerFunc{helloHandler, healthHandler}
server, err := httpserver.NewServer(":8080", patterns, handlers...)
if err != nil {
panic(err)
}
// Run server with graceful shutdown
ctx := context.Background()
if err := httpserver.RunServer(ctx, server, "config/tls/tls.crt", "config/tls/tls.key"); err != nil {
panic(err)
}
}Creates a new HTTP server with the specified routes and handlers.
Parameters:
port: The address to listen on (e.g.,:8080)patterns: Slice of URL patterns (routes)handlers: Variadic slice of handler functions corresponding to each pattern
Returns:
*http.Server: The configured HTTP servererror: Error if patterns and handlers lengths don't match
Example:
patterns := []string{"/api/users", "/api/posts"}
handlers := []http.HandlerFunc{usersHandler, postsHandler}
server, err := httpserver.NewServer(":8080", patterns, handlers...)Runs the server with TLS support and handles graceful shutdown. The server will:
- Start listening with TLS using the provided certificate and key files
- Handle context cancellation
- Listen for OS signals (SIGINT, SIGTERM) for graceful shutdown
- Return errors from server startup failures
Parameters:
ctx: Context for cancellationserver: The HTTP server instance to runcertFile: Path to the TLS certificate filekeyFile: Path to the TLS private key file
Returns:
error: Error from server startup or shutdown
Example:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := httpserver.RunServer(ctx, server, "config/tls/tls.crt", "config/tls/tls.key"); err != nil {
log.Fatal(err)
}Writes a JSON response to the HTTP response writer.
Parameters:
w: The HTTP response writerstatus: HTTP status code (e.g.,http.StatusOK)payload: The data to encode as JSON (any JSON-serializable type)
Example:
httpserver.WriteJSON(w, http.StatusOK, map[string]interface{}{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
})The RunServer function requires TLS certificate and key file paths as parameters. Make sure these files exist before running your server.
Common locations:
- Certificate:
config/tls/tls.crt - Private Key:
config/tls/tls.key
The server supports graceful shutdown through:
- Context Cancellation: Cancel the context passed to
RunServer - OS Signals: Send SIGINT or SIGTERM to the process
The shutdown process allows up to 10 seconds for in-flight requests to complete.
Run tests with:
go test ./...Run tests with coverage:
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.outCurrent test coverage: 78.8%
[Add your license here]