Go

Minimal net/http Server

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The standard library ships a production-quality HTTP server. `http.HandleFunc` registers a function; `http.ListenAndServe` blocks forever serving requests.
Go
Raw
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %s!\n", r.URL.Path[1:])
    })

    http.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })

    log.Println("listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

// Production tip: use http.Server with explicit timeouts instead of ListenAndServe —
//     srv := &http.Server{
//         Addr:         ":8080",
//         ReadTimeout:  5  * time.Second,
//         WriteTimeout: 10 * time.Second,
//         IdleTimeout:  120 * time.Second,
//         Handler:      mux,
//     }
//     log.Fatal(srv.ListenAndServe())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.