Standard library / net/http

http.Handle()

Registers a handler on DefaultServeMux. Prefer an independent mux when composing services. Expected stdout: 'hello\n'.

Formal Syntax & Structure

go syntaxgo
func Handle(pattern string, handler Handler)

Parameters & Attributes

NameTypeDescription
patternstringMethod, host and path pattern for routing.
handlerHandlerHandler to invoke for matching requests.

Working Example

Example Snippetgo
package main
import (  "bytes"  "fmt"  "io"  "mime/multipart"  "net"  "net/http"  "net/http/httptest"  "strings"  "time")
func main() {  http.Handle("/demo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }))  fmt.Println(rec(http.DefaultServeMux, "GET", "/demo").Body.String())}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)  }}
Go Reference