An HTTP server accepts client requests, listens for connections, routes requests to handlers, and returns responses. In Go, the net/http package supplies the server, request, and handler interfaces needed to build one without an external framework. section 8.3
A Go HTTP server connects these pieces:
- An http.Server listens for client connections and invokes the registered handler. section 8.3
- A type implements http.Handler by defining ServeHTTP(http.ResponseWriter, *http.Request). section 8.3
- The handler reads request details and uses ResponseWriter to set headers, choose a status code, and write the response body in that order. section 8.3
- The server runs each registered handler in a separate goroutine, allowing concurrent request handling. section 8.3
A health-check server
A small link-shortener service configures an HTTP address with a default of localhost:8080, initializes structured logging, and runs a server that routes requests to a Health handler. Running the program starts the listener; curl localhost:8080 returns HTTP/1.1 200 OK and an OK body. section 8.3.3
Listing 8.9 Running an HTTP server (link/cmd/linkd/linkd.go)
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"github.com/inancgumus/gobyexample/link/rest"
)
type config struct { #1
http struct { #1
addr string #1
} #1
lg *slog.Logger #1
} #1
#1
func main() {
var cfg config
flag.StringVar(
&cfg.http.addr, "http.addr",
"localhost:8080", "http address to listen on",
)
flag.Parse()
cfg.lg = slog.New( #2
slog.NewTextHandler(os.Stderr, nil), #2
).With("app", "linkd") #2
cfg.lg.Info("starting", "addr", cfg.http.addr)
if err := run(context.Background(), cfg); err != nil {
cfg.lg.Error("failed to start server", "error", err)
os.Exit(1)
}
}
func run(_ context.Context, cfg config) error {
err := http.ListenAndServe( #3
cfg.http.addr, #3
http.HandlerFunc(rest.Health), #3
) #3
if !errors.Is(err, http.ErrServerClosed) { #4
return fmt.Errorf( #4
"server closed unexpectedly: %w", err, #4
) #4
} #4
return nil #4
}
Inspect the complete program structure for configuring an address, creating a slog logger, starting the server, and reporting startup failures. section 8.3.3










