Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 22, 2023 03:23
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/8eff34243e8cfef01271894b52f2b40b to your computer and use it in GitHub Desktop.
Save ostretsov/8eff34243e8cfef01271894b52f2b40b to your computer and use it in GitHub Desktop.
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