Created
July 22, 2023 03:22
-
-
Save ostretsov/73e3c782acbb83407ccc14db4592f8b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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