Standard library / net/http
http.Server
Configures an HTTP server, its handler and timeouts. Reuse explicit configuration and shut down gracefully. Expected stdout: 'hello\ntrue\n'.
Formal Syntax & Structure
go syntaxgo
type Server struct { Addr string
Handler Handler
DisableGeneralOptionsHandler bool
TLSConfig *tls.Config
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
ConnState func(net.Conn, ConnState)
ErrorLog *log.Logger
BaseContext func(net.Listener) context.Context
ConnContext func(ctx context.Context, c net.Conn) context.Context
}Working Example
Example Snippetgo
package main
import ( "bytes" "errors" "fmt" "io" "mime/multipart" "net" "net/http" "net/http/httptest" "strings" "time")
func main() { s, u, done := localServer() defer s.Close() c := &http.Client{Timeout: time.Second} r := must(c.Get(u)) defer r.Body.Close() fmt.Println(string(must(io.ReadAll(r.Body)))) check(s.Close()) fmt.Println(errors.Is(<-done, http.ErrServerClosed))}func rec(h http.Handler, method, path string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, nil)) return w}func fixture() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }))}func localServer() (*http.Server, string, chan error) { l := must(net.Listen("tcp4", "127.0.0.1:0")) s := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }), ReadHeaderTimeout: time.Second} done := make(chan error, 1) go func() { done <- s.Serve(l) }() return s, "http://" + l.Addr().String(), done}func form() *http.Request { r := httptest.NewRequest("POST", "/?q=query", strings.NewReader("q=body&name=Go")) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") return r}func multipartReq() *http.Request { var b bytes.Buffer w := multipart.NewWriter(&b) f := must(w.CreateFormFile("upload", "demo.txt")) _, e := io.WriteString(f, "hello") check(e) check(w.Close()) r := httptest.NewRequest("POST", "/", &b) r.Header.Set("Content-Type", w.FormDataContentType()) return r}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}