Standard library / net/http
http.Serve()
Serves HTTP on an existing listener using the supplied handler. Closing the listener ends the accept loop with an error. Expected stdout: 'hello\ntrue\n'.
Formal Syntax & Structure
go syntaxgo
func Serve(l net.Listener, handler Handler) errorParameters & Attributes
| Name | Type | Description |
|---|---|---|
| l | net.Listener | Listener owned and closed by the serving operation. |
| handler | Handler | Handler to invoke for matching requests. |
Return Value
error
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "fmt" "io" "net" "net/http" "time")
func main() { l := must(net.Listen("tcp4", "127.0.0.1:0")) done := make(chan error, 1) go func() { done <- http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") })) }() c := &http.Client{Timeout: time.Second} r := must(c.Get("http://" + l.Addr().String())) fmt.Println(string(must(io.ReadAll(r.Body)))) check(r.Body.Close()) check(l.Close()) fmt.Println(<-done != nil)}
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) }}