Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 22, 2023 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/73e3c782acbb83407ccc14db4592f8b9 to your computer and use it in GitHub Desktop.
Save ostretsov/73e3c782acbb83407ccc14db4592f8b9 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
)
func Example_httpServerContext() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tcpAddr, ok := r.Context().Value(http.LocalAddrContextKey).(*net.TCPAddr); ok {
fmt.Println("network:", tcpAddr.Network())
}
if server, ok := r.Context().Value(http.ServerContextKey).(*http.Server); ok {
fmt.Println("halt the server")
_ = server.Close()
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`Писать уже некуда: сервер остановлен, соединения разорваны`))
}))
defer srv.Close()
req := httptest.NewRequest(http.MethodGet, srv.URL, nil)
res, err := http.DefaultClient.Do(req)
fmt.Println("request is interrupted:", errors.Is(err, io.EOF))
fmt.Println("response is nil:", res == nil)
// Output:
// network: tcp
// halt the server
// request is interrupted: true
// response is nil: true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment