Go HTTP Handlers
Keep request methods and paths explicit.
How it works
An http.Handler receives a ResponseWriter and Request. Decide the method and path contract before writing a success body. Once a header or body is written, you cannot replace the status as if nothing had been sent. A response recorder is useful for unit tests; a later project also uses real loopback HTTP.
Run this Go example
Install Go separately from the official Go downloads and check go version in a new terminal. The reviewed baseline is Go 1.27.3 on Windows amd64; the authored syntax and standard-library APIs require Go 1.22 or newer. Save the complete source below as http-handlers.go in a learning folder, then run go run http-handlers.go from that folder. These examples use only the standard library.
Bhylu has no Go browser runner. Apache, MySQL, PHP and the JavaScript or Python playground are not required to run these files. File examples own a temporary directory; HTTP client examples create an ephemeral loopback server and close it. They do not contact an external API.
Download the complete http-handlers.go · Download all source files with hash checks
For the optional collection download, save download-examples.mjs in a new learning folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/go/. The downloader refuses an existing bhylu-go-examples folder and installs or executes no Go code.
Example
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func health(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
http.NotFound(w, r)
return
}
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "ready")
}
func main() {
for _, method := range []string{"GET", "POST"} {
request := httptest.NewRequest(method, "/health", nil)
recorder := httptest.NewRecorder()
health(recorder, request)
fmt.Println(recorder.Code, strings.TrimSpace(recorder.Body.String()))
}
}
Expected result
200 ready 405 method not allowed
The GET request succeeds and the POST request is refused with Allow: GET. This page exercises the actual handler in memory and does not claim a network test for the recorder.
For language rules and APIs, use the Go language specification and standard-library documentation. The fictional examples are learning fixtures, not a deployed parcel service.