### Example: HTTP/2 with EnableHTTP2 and StartTLS Source: https://pkg.go.dev/net/http/httptest Example of starting an unstarted server with HTTP/2 enabled via EnableHTTP2 and StartTLS, then using the client to make a request. The output is 'Hello, HTTP/2.0'. ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s", r.Proto) })) ts.EnableHTTP2 = true ts.StartTLS() defer ts.Close() res, err := ts.Client().Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) } ``` ```text Output: Hello, HTTP/2.0 ``` -------------------------------- ### Example: NewServer with HTTP/1.1 Source: https://pkg.go.dev/net/http/httptest Complete example of using httptest.NewServer to create a test server, send a GET request, and print the response body. The output is 'Hello, client'. ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) } ``` ```text Output: Hello, client ``` -------------------------------- ### Example: HTTP/2 Server Usage Source: https://pkg.go.dev/net/http/httptest Example demonstrating how to create an unstarted test server, enable HTTP/2, start it with TLS, and make a request using the server's client. ```APIDOC ## Example: HTTP/2 Server Usage ### Description Example demonstrating how to create an unstarted test server, enable HTTP/2, start it with TLS, and make a request using the server's client. ### Code ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s", r.Proto) })) ts.EnableHTTP2 = true ts.StartTLS() defer ts.Close() res, err := ts.Client().Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) } ``` ### Output ``` Hello, HTTP/2.0 ``` ``` -------------------------------- ### ListenAndServe example: hello world server Source: https://pkg.go.dev/net/http Complete example for the ListenAndServe function. It defines a handler that writes 'Hello, world!' and registers it for the '/hello' pattern, then starts the server on port 8080. ```go package main import ( "io" "log" "net/http" ) func main() { // Hello world, the web server helloHandler := func(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Hello, world!\n") } http.HandleFunc("/hello", helloHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Example: DumpResponse Source: https://pkg.go.dev/net/http/httputil Complete example demonstrating DumpResponse. It creates a test server, sends a GET request, and dumps the response with the body. The output is printed as a quoted string. ```go package main import ( "fmt" "log" "net/http" "net/http/httptest" "net/http/httputil" ) func main() { const body = "Go is a general-purpose language designed with systems programming in mind." ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT") fmt.Fprintln(w, body) })) defer ts.Close() resp, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } defer resp.Body.Close() dump, err := httputil.DumpResponse(resp, true) if err != nil { log.Fatal(err) } fmt.Printf("%q", dump) } ``` ```text Output: "HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n" ``` -------------------------------- ### Output placeholder for Get example Source: https://pkg.go.dev/net/http Placeholder for the output of the Get example. The actual output is not shown. ```text Output: ``` -------------------------------- ### Package example: tracing HTTP client request with httptrace Source: https://pkg.go.dev/net/http/httptrace This example creates an HTTP GET request, defines a ClientTrace with GotConn and DNSDone hooks, attaches the trace to the request context using WithClientTrace, and performs the request with http.DefaultTransport.RoundTrip. The output is empty as shown. ```Go package main import ( "fmt" "log" "net/http" "net/http/httptrace" ) func main() { req, _ := http.NewRequest("GET", "http://example.com", nil) trace := &httptrace.ClientTrace{ GotConn: func(connInfo httptrace.GotConnInfo) { fmt.Printf("Got Conn: %+v\n", connInfo) }, DNSDone: func(dnsInfo httptrace.DNSDoneInfo) { fmt.Printf("DNS Info: %+v\n", dnsInfo) }, } req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) _, err := http.DefaultTransport.RoundTrip(req) if err != nil { log.Fatal(err) } } ``` ```text Output: ``` -------------------------------- ### Start a server with DefaultServeMux Source: https://pkg.go.dev/net/http Shows how to register handlers with http.Handle and http.HandleFunc and start a server with http.ListenAndServe using the default mux. ```go http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", nil)) ``` -------------------------------- ### Example: Use HTTP/1 and HTTP/2 with Protocols.SetHTTP1 and SetHTTP2 Source: https://pkg.go.dev/net/http Configures an http.Transport to use either HTTP/1 or HTTP/2 by cloning the default transport, enabling both protocols, and creating an http.Client with that transport. The example makes a GET request to http://www.google.com/robots.txt. ```go package main import ( "log" "net/http" ) func main() { t := http.DefaultTransport.(*http.Transport).Clone() // Use either HTTP/1 and HTTP/2. t.Protocols = new(http.Protocols) t.Protocols.SetHTTP1(true) t.Protocols.SetHTTP2(true) cli := &http.Client{Transport: t} res, err := cli.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } res.Body.Close() } ``` -------------------------------- ### Example: Using cookiejar.New with an HTTP client Source: https://pkg.go.dev/net/http/cookiejar This example starts a test server that sets and updates a cookie, creates a cookiejar with the publicsuffix list, and uses it with an HTTP client. It prints the cookies after each request. The output shows the cookie value changing from 'Chocolate Chip' to 'Oatmeal Raisin'. ```go // Start a server to give us cookies. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if cookie, err := r.Cookie("Flavor"); err != nil { http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"}) } else { cookie.Value = "Oatmeal Raisin" http.SetCookie(w, cookie) } })) defer ts.Close() u, err := url.Parse(ts.URL) if err != nil { log.Fatal(err) } // All users of cookiejar should import "golang.org/x/net/publicsuffix" jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) if err != nil { log.Fatal(err) } client := &http.Client{ Jar: jar, } if _, err = client.Get(u.String()); err != nil { log.Fatal(err) } fmt.Println("After 1st request:") for _, cookie := range jar.Cookies(u) { fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value) } if _, err = client.Get(u.String()); err != nil { log.Fatal(err) } fmt.Println("After 2nd request:") for _, cookie := range jar.Cookies(u) { fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value) } ``` ```go Output: After 1st request: Flavor: Chocolate Chip After 2nd request: Flavor: Oatmeal Raisin ``` -------------------------------- ### func (s *Server) Start() Source: https://pkg.go.dev/net/http/httptest Starts the test server on a local loopback network interface. The server should have been created by NewTestServer or NewUnstartedServer. ```APIDOC ## func (s *Server) Start() ### Description Starts the test server on a local loopback network interface. The server should have been created by NewTestServer or NewUnstartedServer. ### Method Start ### Signature func (s *Server) Start() ### Parameters None ### Return Value None ### Usage Example ```go server := httptest.NewUnstartedServer(handler) server.Start() ``` ``` -------------------------------- ### func (s *Server) Start() Source: https://pkg.go.dev/net/http/httptest Starts the server from an unstarted state. It is an error to call Start on an already started server. ```APIDOC ## func (s *Server) Start() ### Description Start starts the server from an unstarted state. It is an error to call Start on an already started server. ### Method N/A (method) ### Endpoint N/A (method) ### Parameters None. ### Returns None. ### Example ```go server.Start() ``` ``` -------------------------------- ### ResponseRecorder example with output Source: https://pkg.go.dev/net/http/httptest Complete example showing how to use httptest.NewRequest and httptest.NewRecorder to test a handler. The handler writes an HTML string, and the example prints the status code, Content-Type header, and body. The output is shown as displayed. ```go package main import ( "fmt" "io" "net/http" "net/http/httptest" ) func main() { handler := func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello World!") } req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.StatusCode) fmt.Println(resp.Header.Get("Content-Type")) fmt.Println(string(body)) } ``` ```text Output: 200 text/html; charset=utf-8 Hello World! ``` -------------------------------- ### HandleFunc example: two handlers Source: https://pkg.go.dev/net/http Complete example for the HandleFunc function. It defines two handler functions that write different messages, registers them for the '/' and '/endpoint' patterns, and starts the server on port 8080. ```go package main import ( "io" "log" "net/http" ) func main() { h1 := func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "Hello from a HandleFunc #1!\n") } h2 := func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "Hello from a HandleFunc #2!\n") } http.HandleFunc("/", h1) http.HandleFunc("/endpoint", h2) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Example: Basic Server Usage Source: https://pkg.go.dev/net/http/httptest Example demonstrating how to create a test server with httptest.NewServer, make an HTTP request to it, and read the response body. ```APIDOC ## Example: Basic Server Usage ### Description Example demonstrating how to create a test server with httptest.NewServer, make an HTTP request to it, and read the response body. ### Code ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) } ``` ### Output ``` Hello, client ``` ``` -------------------------------- ### Example: ServeMux.Handle with root and API handlers Source: https://pkg.go.dev/net/http Example from the documentation showing how to register an API handler and a root handler using ServeMux.Handle and ServeMux.HandleFunc. The root handler checks the URL path to avoid matching all paths. ```go package main import ( "fmt" "net/http" ) type apiHandler struct{} func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} func main() { mux := http.NewServeMux() mux.Handle("/api/", apiHandler{}) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // The "/" pattern matches everything, so we need to check // that we're at the root here. if req.URL.Path != "/" { http.NotFound(w, req) return } fmt.Fprintf(w, "Welcome to the home page!") }) } ``` -------------------------------- ### Example: http.Get Source: https://pkg.go.dev/net/http Complete example of using http.Get to fetch a URL, read the response body, and check for errors. It prints the body to standard output. ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } body, err := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode > 299 { log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body) } if err != nil { log.Fatal(err) } fmt.Printf("%s", body) } ``` -------------------------------- ### NewTLSServer example Source: https://pkg.go.dev/net/http/httptest Example usage of NewTLSServer: creates a TLS test server, uses its client to make a request, and prints the response. ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() client := ts.Client() res, err := client.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) } ``` ```text Output: Hello, client ``` -------------------------------- ### ListenAndServeTLS example Source: https://pkg.go.dev/net/http Example of using ListenAndServeTLS to serve HTTPS on port 8443. It sets up a handler that returns 'Hello, TLS!' and logs a fatal error if the server fails. The example notes that cert.pem and key.pem can be generated using generate_cert.go in crypto/tls. ```go package main import ( "io" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Hello, TLS!\n") }) // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/") err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil) log.Fatal(err) } ``` -------------------------------- ### Example: Serve only HTTP/1 with Protocols.SetHTTP1 Source: https://pkg.go.dev/net/http Configures an http.Server to serve only HTTP/1 by creating a new Protocols, enabling HTTP1, and calling ListenAndServeTLS. The example uses cert.pem and key.pem files. ```go package main import ( "log" "net/http" ) func main() { srv := http.Server{ Addr: ":8443", } // Serve only HTTP/1. srv.Protocols = new(http.Protocols) srv.Protocols.SetHTTP1(true) log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem")) } ``` -------------------------------- ### Create a custom Server with timeouts Source: https://pkg.go.dev/net/http Shows how to create a custom http.Server with Addr, Handler, ReadTimeout, WriteTimeout, and MaxHeaderBytes, and start it with ListenAndServe. ```go s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ``` -------------------------------- ### func (s *Server) StartTLS() Source: https://pkg.go.dev/net/http/httptest Starts the server with TLS from an unstarted state. It is an error to call StartTLS on an already started server. ```APIDOC ## func (s *Server) StartTLS() ### Description StartTLS starts the server with TLS from an unstarted state. It is an error to call StartTLS on an already started server. ### Method N/A (method) ### Endpoint N/A (method) ### Parameters None. ### Returns None. ### Example ```go server.StartTLS() ``` ``` -------------------------------- ### ReverseProxy Example Source: https://pkg.go.dev/net/http/httputil Example demonstrating how to use ReverseProxy with the Rewrite field to proxy requests to a backend server. ```APIDOC ## ReverseProxy Example ### Description Example of using ReverseProxy with the Rewrite field to relay requests to a backend server. ### Code ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" "net/http/httputil" "net/url" ) func main() { backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "this call was relayed by the reverse proxy") })) defer backendServer.Close() rpURL, err := url.Parse(backendServer.URL) if err != nil { log.Fatal(err) } frontendProxy := httptest.NewServer(&httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.SetXForwarded() r.SetURL(rpURL) }, }) defer frontendProxy.Close() resp, err := http.Get(frontendProxy.URL) if err != nil { log.Fatal(err) } b, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) } ``` ### Output ``` this call was relayed by the reverse proxy ``` ``` -------------------------------- ### NotFoundHandler example Source: https://pkg.go.dev/net/http Example usage of http.NotFoundHandler to return 404 for a specific path while other paths return 200. ```go package main import ( "fmt" "log" "net/http" ) func newPeopleHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "This is the people handler.") }) } func main() { mux := http.NewServeMux() // Create sample handler to returns 404 mux.Handle("/resources", http.NotFoundHandler()) // Create sample handler that returns 200 mux.Handle("/resources/people/", newPeopleHandler()) log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### FileServer example: dot file hiding Source: https://pkg.go.dev/net/http Example of a custom http.FileSystem that hides dot files from being served. It wraps the FileSystem and File to filter out files starting with a period and returns a 403 permission error for paths containing dot files. ```go package main import ( "io" "io/fs" "log" "net/http" "strings" ) // containsDotFile reports whether name contains a path element starting with a period. // The name is assumed to be a delimited by forward slashes, as guaranteed // by the http.FileSystem interface. func containsDotFile(name string) bool { parts := strings.Split(name, "/") for _, part := range parts { if strings.HasPrefix(part, ".") { return true } } return false } // dotFileHidingFile is the http.File use in dotFileHidingFileSystem. // It is used to wrap the Readdir method of http.File so that we can // remove files and directories that start with a period from its output. type dotFileHidingFile struct { http.File } // Readdir is a wrapper around the Readdir method of the embedded File // that filters out all files that start with a period in their name. func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) { files, err := f.File.Readdir(n) for _, file := range files { // Filters out the dot files if !strings.HasPrefix(file.Name(), ".") { fis = append(fis, file) } } if err == nil && n > 0 && len(fis) == 0 { err = io.EOF } return } // dotFileHidingFileSystem is an http.FileSystem that hides // hidden "dot files" from being served. type dotFileHidingFileSystem struct { http.FileSystem } // Open is a wrapper around the Open method of the embedded FileSystem // that serves a 403 permission error when name has a file or directory // with whose name starts with a period in its path. func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) { if containsDotFile(name) { // If dot file, return 403 response return nil, fs.ErrPermission } file, err := fsys.FileSystem.Open(name) if err != nil { return nil, err } return dotFileHidingFile{file}, nil } func main() { fsys := dotFileHidingFileSystem{http.Dir(".")} http.Handle("/", http.FileServer(fsys)) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Start HTTP server for pprof Source: https://pkg.go.dev/net/http/pprof If the application is not already running an HTTP server, start one on localhost:6060. This code is added to the main function after importing net/http and log. ```go go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() ``` -------------------------------- ### Server.Start and Server.StartTLS Source: https://pkg.go.dev/net/http/httptest Server.Start and Server.StartTLS start the server on a loopback interface with a system-chosen port. Start serves HTTP, while StartTLS serves HTTPS. The server's URL field is set to a base URL containing the server's address. ```APIDOC ## Server.Start and Server.StartTLS ### Description Server.Start and Server.StartTLS start the server on a loopback interface with a system-chosen port. Start serves HTTP, while StartTLS serves HTTPS. The server's URL field is set to a base URL containing the server's address. ### Methods - **Server.Start()** - Starts the server serving HTTP. - **Server.StartTLS()** - Starts the server serving HTTPS. ### Behavior - The server listens on a system-chosen port on the loopback interface. - The Server.URL field is set to a base URL containing the server's address. - When using the loopback network, the http.Client returned by Server.Client is configured to send requests with a hostname of "example.com" or a subdomain of ".example.com" to the server. - Requests may also be sent to the server's loopback address. ### Example ```go server := httptest.NewTestServer(t, handler) server.Start() client := server.Client() // This request is sent to the test server. _, _ = server.Client().Get(server.URL + "/") // This request (using http.DefaultClient) is also sent to the test server, // since server.URL contains the server's local IP address. _, _ = http.Get(server.URL + "/") ``` ``` -------------------------------- ### Handle example: count handler Source: https://pkg.go.dev/net/http Complete example for the Handle function. It defines a countHandler struct with a mutex and an integer, and its ServeHTTP method increments the count and writes it to the response. The main function registers the handler for the '/count' pattern and starts the server on port 8080. ```go package main import ( "fmt" "log" "net/http" "sync" ) type countHandler struct { mu sync.Mutex // guards n n int } func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mu.Lock() defer h.mu.Unlock() h.n++ fmt.Fprintf(w, "count is %d\n", h.n) } func main() { http.Handle("/count", new(countHandler)) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### FileServer example: simple static webserver Source: https://pkg.go.dev/net/http Complete example of a simple static webserver using FileServer with http.Dir. It serves files from /usr/share/doc on port 8080. ```go package main import ( "log" "net/http" ) func main() { // Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) } ``` -------------------------------- ### FileServer example: StripPrefix Source: https://pkg.go.dev/net/http Example of using http.StripPrefix to serve a directory on disk under an alternate URL path. It modifies the request URL's path before the FileServer sees it. ```go package main import ( "net/http" ) func main() { // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) } ``` -------------------------------- ### func NewUnstartedServer(handler http.Handler) *Server Source: https://pkg.go.dev/net/http/httptest Returns a new Server but does not start it. The caller must call Start or StartTLS to begin serving. ```APIDOC ## func NewUnstartedServer(handler http.Handler) *Server ### Description NewUnstartedServer returns a new Server but does not start it. The caller must call Start or StartTLS to begin serving. ### Method N/A (function) ### Endpoint N/A (function) ### Parameters - **handler** (http.Handler) - Required - The HTTP handler to serve. ### Returns - **\*Server** - The unstarted server. ### Example ```go server := httptest.NewUnstartedServer(handler) server.Start() ``` ``` -------------------------------- ### Create a test server and send a request Source: https://pkg.go.dev/net/http/httptest Example usage of httptest.NewTestServer and Server.Client to send a request to the test server. ```go // Create a test server and send a request to it. server := httptest.NewTestServer(t, handler) resp, err := server.Client().Get("http://www.example.com/") ``` -------------------------------- ### func (s *Server) StartTLS() Source: https://pkg.go.dev/net/http/httptest Starts TLS on a server on a local loopback network interface. The server should have been created by NewTestServer or NewUnstartedServer. ```APIDOC ## func (s *Server) StartTLS() ### Description Starts TLS on a server on a local loopback network interface. The server should have been created by NewTestServer or NewUnstartedServer. ### Method StartTLS ### Signature func (s *Server) StartTLS() ### Parameters None ### Return Value None ### Usage Example ```go server := httptest.NewUnstartedServer(handler) server.StartTLS() ``` ``` -------------------------------- ### DumpRequestOut example with output Source: https://pkg.go.dev/net/http/httputil Example of using httputil.DumpRequestOut to dump an outgoing client request. The request is a PUT to www.example.org with a body. The output shows the HTTP/1.1 wire format including headers added by the transport. ```go package main import ( "fmt" "log" "net/http" "net/http/httputil" "strings" ) func main() { const body = "Go is a general-purpose language designed with systems programming in mind." req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body)) if err != nil { log.Fatal(err) } dump, err := httputil.DumpRequestOut(req, true) if err != nil { log.Fatal(err) } fmt.Printf("%q", dump) } ``` ```text Output: "PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind." ``` -------------------------------- ### Configure a test server before using (httptest.NewTestServer) Source: https://pkg.go.dev/net/http/httptest Shows how to set server configuration (MaxHeaderBytes) before the first use. Configuration must not be changed after calling Client, Start, or StartTLS. ```go // Configure a test server before using. server := httptest.NewTestServer(t, handler) server.Config.MaxHeaderBytes = 1024 resp, err := server.Client().Get("http://www.example.com/") ``` -------------------------------- ### CrossOriginProtection example Source: https://pkg.go.dev/net/http Shows how to use CrossOriginProtection.Handler to block non-safe cross-origin browser requests. The example sets up an HTTP server with a /hello handler and wraps the mux with the protection handler. ```go package main import ( "io" "log" "net/http" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "request allowed\n") }) srv := http.Server{ Addr: ":8080", ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, // Use CrossOriginProtection.Handler to block all non-safe cross-origin // browser requests to mux. Handler: http.NewCrossOriginProtection().Handler(mux), } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### ReverseProxy example with Rewrite Source: https://pkg.go.dev/net/http/httputil Complete example of using httputil.ReverseProxy with a Rewrite function to relay requests to a backend server. It sets up a backend httptest server, a frontend proxy, and makes a request, printing the response body. The output is 'this call was relayed by the reverse proxy'. ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" "net/http/httputil" "net/url" ) func main() { backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "this call was relayed by the reverse proxy") })) defer backendServer.Close() rpURL, err := url.Parse(backendServer.URL) if err != nil { log.Fatal(err) } frontendProxy := httptest.NewServer(&httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.SetXForwarded() r.SetURL(rpURL) }, }) defer frontendProxy.Close() resp, err := http.Get(frontendProxy.URL) if err != nil { log.Fatal(err) } b, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) } ``` ```text Output: this call was relayed by the reverse proxy ``` -------------------------------- ### Example: Setting HTTP Trailers with ResponseWriter Source: https://pkg.go.dev/net/http Shows how to declare and set HTTP trailers in a handler. Trailers must be declared before WriteHeader or Write, and are sent after the response body. ```go package main import ( "io" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) { // Before any call to WriteHeader or Write, declare // the trailers you will set during the HTTP // response. These three headers are actually sent in // the trailer. w.Header().Set("Trailer", "AtEnd1, AtEnd2") w.Header().Add("Trailer", "AtEnd3") w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header w.WriteHeader(http.StatusOK) w.Header().Set("AtEnd1", "value 1") io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n") w.Header().Set("AtEnd2", "value 2") w.Header().Set("AtEnd3", "value 3") // These will appear as trailers. }) } ``` -------------------------------- ### NewUnstartedServer Source: https://pkg.go.dev/net/http/httptest Returns a new Server listening on a local network loopback interface. It does not start the server. After changing the server's configuration, the caller should call Server.Start or Server.StartTLS. ```APIDOC ## NewUnstartedServer ### Description Returns a new Server listening on a local network loopback interface. It does not start the server. After changing the server's configuration, the caller should call Server.Start or Server.StartTLS. The caller should call Server.Close when finished, to shut it down. ### Function Signature ```go func NewUnstartedServer(handler http.Handler) *Server ``` ### Parameters - **handler** (http.Handler) - Required - The HTTP handler to serve. ### Returns - **\*Server** - A new unstarted test server. ``` -------------------------------- ### DumpRequest example with output Source: https://pkg.go.dev/net/http/httputil Example of using httputil.DumpRequest to dump an incoming request in a test server. The server echoes the dump as a quoted string, and the client sends a POST request with a body. The output shows the HTTP/1.1 wire format including headers and body. ```go package main import ( "fmt" "io" "log" "net/http" "net/http/httptest" "net/http/httputil" "strings" ) func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dump, err := httputil.DumpRequest(r, true) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } fmt.Fprintf(w, "%q", dump) })) defer ts.Close() const body = "Go is a general-purpose language designed with systems programming in mind." req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body)) if err != nil { log.Fatal(err) } req.Host = "www.example.org" resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) } ``` ```text Output: "POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nContent-Length: 75\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind." ``` -------------------------------- ### Example: copy inbound X-Forwarded-For before SetXForwarded Source: https://pkg.go.dev/net/http/httputil Example rewrite function that copies the inbound request's X-Forwarded-For header to the outbound request before calling SetXForwarded, preserving the default ReverseProxy behavior of appending to the inbound header. ```go rewriteFunc := func(r *httputil.ProxyRequest) { r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] r.SetXForwarded() } ``` -------------------------------- ### Make HTTP requests with Get, Post, and PostForm Source: https://pkg.go.dev/net/http Shows how to use http.Get, http.Post, and http.PostForm to make HTTP requests. The caller must close the response body when finished. ```go resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) ``` -------------------------------- ### Loopback server with Server.Start and Client Source: https://pkg.go.dev/net/http/httptest Shows how to start a loopback server with httptest.NewTestServer and Server.Start, then use the returned client and URL to send requests. The client is configured to send requests with hostname 'example.com' or subdomain '.example.com' to the server. ```go server := httptest.NewTestServer(t, handler) server.Start() client := server.Client() // This request is sent to the test server. _, _ = server.Client().Get(server.URL + "/") // This request (using http.DefaultClient) is also sent to the test server, // since server.URL contains the server's local IP address. _, _ = http.Get(server.URL + "/") ``` -------------------------------- ### Get Source: https://pkg.go.dev/net/http Sends an HTTP GET request to the specified URL and returns the response. It is a wrapper around http.DefaultClient.Get. ```APIDOC ## Get ### Description Sends an HTTP GET request to the specified URL and returns the response. It is a wrapper around http.DefaultClient.Get. ### Method func Get(url string) (resp *Response, err error) ### Parameters - **url** (string) - Required - The URL to send the GET request to. ### Returns - **\*Response** - The HTTP response. - **error** - An error if the request fails. ``` -------------------------------- ### Using http.Dir with FileServer Source: https://pkg.go.dev/net/http Shows how to use the operating system's file system implementation with http.Dir. This is a simple way to serve files from a directory. ```go http.Handle("/", http.FileServer(http.Dir("/tmp"))) ``` -------------------------------- ### Create a Transport with custom settings Source: https://pkg.go.dev/net/http Shows how to create an http.Transport with MaxIdleConns, IdleConnTimeout, and DisableCompression, and use it with a Client. Clients and Transports are safe for concurrent use and should be created once and re-used. ```go tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com") ``` -------------------------------- ### Get function signature Source: https://pkg.go.dev/net/http Signature for the net/http.Get function. It issues a GET request to the specified URL and returns a Response and error. ```go func Get(url string) (resp *Response, err error) ``` -------------------------------- ### func Get(url string) (resp *Response, err error) Source: https://pkg.go.dev/net/http Get issues a GET to the specified URL. It follows redirects up to a maximum of 10. An error is returned if there were too many redirects or if there was an HTTP protocol error. The caller should close resp.Body when done reading from it. ```APIDOC ## func Get(url string) (resp *Response, err error) ### Description Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects: 301 (Moved Permanently), 302 (Found), 303 (See Other), 307 (Temporary Redirect), 308 (Permanent Redirect). An error is returned if there were too many redirects or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out. When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. Get is a wrapper around DefaultClient.Get. ### Function Signature func Get(url string) (resp *Response, err error) ### Parameters - **url** (string) - Required - The URL to send the GET request to. ### Return Values - **resp** (*Response) - The HTTP response. - **err** (error) - An error if the request failed. ### Example ```go package main import ( "fmt" "io" "log" "net/http" ) func main() { res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } body, err := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode > 299 { log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body) } if err != nil { log.Fatal(err) } fmt.Printf("%s", body) } ``` ``` -------------------------------- ### func (c *Client) Get(url string) (resp *Response, err error) Source: https://pkg.go.dev/net/http Sends a GET request to the specified URL. ```APIDOC ## Client.Get ### Description Sends a GET request to the specified URL. ### Method Signature func (c *Client) Get(url string) (resp *Response, err error) ### Parameters - **url** (string) - Required - The URL to request. ### Returns - **Response** - The response. - **error** - Any error encountered. ``` -------------------------------- ### Create a Client with redirect policy and custom headers Source: https://pkg.go.dev/net/http Shows how to create an http.Client with a CheckRedirect function and use it to make requests with custom headers via NewRequest and client.Do. ```go client := &http.Client{ CheckRedirect: redirectPolicyFunc, } resp, err := client.Get("http://example.com") // ... req, err := http.NewRequest("GET", "http://example.com", nil) // ... req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req) // ... ``` -------------------------------- ### Redirect codes followed by Get and Head Source: https://pkg.go.dev/net/http List of HTTP redirect status codes that Get and Head follow, up to a maximum of 10 redirects. ```text 301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect) ``` -------------------------------- ### func (c *Client) Get(url string) (resp *Response, err error) Source: https://pkg.go.dev/net/http Get issues a GET to the specified URL. It follows redirects for 301, 302, 303, 307, and 308 status codes after calling Client.CheckRedirect. An error is returned if CheckRedirect fails or if there was an HTTP protocol error, but not for non-2xx responses. ```APIDOC ## func (c *Client) Get(url string) (resp *Response, err error) ### Description Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the Client.CheckRedirect function: 301 (Moved Permanently), 302 (Found), 303 (See Other), 307 (Temporary Redirect), 308 (Permanent Redirect). An error is returned if the Client.CheckRedirect function fails or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. ### Method Get ### Signature func (c *Client) Get(url string) (resp *Response, err error) ### Parameters - **url** (string) - Required - The URL to send the GET request to. ### Returns - **resp** (*Response) - The HTTP response. When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. - **err** (error) - Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out. ### Behavior - To make a request with custom headers, use NewRequest and Client.Do. - To make a request with a specified context.Context, use NewRequestWithContext and Client.Do. ```