HTTP server made from scratch in Go 🚀✨
Description • Features • Quick Start • Documentation • Testing
This project is a lightweight and easy to use HTTP server written in Go that handles TCP connections and implements the RFC 7230 (HTTP/1.1) standard. It's designed to make building web APIs and applications simple and straightforward.
- Supports HTTP methods: Handle
GET
,POST
,PUT
,DELETE
, and more. - Routing:
Dynamic
andstatic
route handling. - Built-in Timeouts: Automatically
close slow connections
and prevent resource locks. - Request Timeout Handling: Gracefully stop long-running requests by using
contexts
. - Custom Middleware Support: Easily extend server’s functionality by adding
reusable logic
to handlers. - Graceful Shutdown: Ensures safe server termination, allowing ongoing requests to
complete
ortime out
before shutting down. - Ease of Usage:
Start quickly
withminimal setup
and easily add new features. - Test Coverage:
90%+
of the code is tested for reliability. - RFC Compliance: Compatibility with HTTP/1.1 standards.
go get github.com/fmich7/http
package main
import (
"fmt"
"github.com/fmich7/http"
)
// Logging middleware
func LoggingMiddleware(next http.HTTPHandler) http.HTTPHandler {
return func(r *http.HTTPRequest, w http.ResponseWriter) {
fmt.Printf("Received %s request for %s\n", r.Method, r.URL)
// Call the next handler
next(r, w)
}
}
// Handler function for the /hello/{who} route
// {who} is a dynamic route parameter
func HelloHandler(r *http.HTTPRequest, w http.ResponseWriter) {
w.SetStatus(200)
w.SetHeader("Content-Type", "text/html")
w.Write([]byte(fmt.Sprintf("<h1>Hello, %s!</h1>", r.Params["who"])))
}
func main() {
router := http.NewHTTPRouter()
server := http.NewServer(":3000", router)
// Register a handler with middleware
router.HandlerFunc("GET", "/hello/{who}", LoggingMiddleware(HelloHandler))
// Start the server and automatically handle graceful shutdown
if err := server.Start(); err != nil {
fmt.Println("Error occurred while starting the server:", err)
}
}
View more examples in the
/examples
directory
Explore the full documentation for this package on
# go test -v -timeout 5s -race ./...
make test
# Generate test coverage file
make coverage