Created
July 22, 2023 03:23
-
-
Save ostretsov/8eff34243e8cfef01271894b52f2b40b 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 ( | |
"context" | |
"fmt" | |
"net" | |
"net/http" | |
"net/http/httptest" | |
) | |
func Example_httpServerConnContext() { | |
srv := http.Server{ | |
Addr: "localhost:9090", | |
ConnContext: func(ctx context.Context, c net.Conn) context.Context { | |
return context.WithValue(ctx, "local-addr", c.LocalAddr()) | |
}, | |
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
if addr, ok := r.Context().Value("local-addr").(net.Addr); ok { | |
fmt.Println(addr) | |
} | |
}), | |
} | |
defer srv.Close() | |
go func() { | |
_ = srv.ListenAndServe() | |
}() | |
req := httptest.NewRequest(http.MethodGet, srv.Addr, nil) | |
res := httptest.NewRecorder() | |
srv.Handler.ServeHTTP(res, req) | |
// Output: | |
// localhost:9090 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment