create a http server with a head route in go

Here's an example code for creating an HTTP server with a HEAD route in Go:

main.go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", helloHandler)
    http.HandleFunc("/hello/", helloHandler) // allow trailing slash
    http.HandleFunc("/health", healthCheckHandler)
    http.HandleFunc("/", defaultHandler)

    fmt.Println("Listening on port 8080")
    http.ListenAndServe(":8080", nil)
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "HEAD" {
        return
    }

    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, "Hello, World!")
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "HEAD" {
        return
    }

    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, "OK")
}

func defaultHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprint(w, "Not Found")
}
845 chars
40 lines

In this example, we define four different routes: /hello, /health, /hello/ (with a trailing slash), and the default route for anything else. The helloHandler and healthCheckHandler functions handle GET and HEAD requests, and the defaultHandler function returns a 404 Not Found HTTP status code. The fmt.Fprint function writes a response body to the client, and w.WriteHeader sets the HTTP status code for the response. Finally, we use http.ListenAndServe to start the server listening on port 8080, and pass nil as the handler, which means we're using the default ServeMux.

related categories

gistlibby LogSnag