context.go
TLDR
This file in the Demo Projects
project, located at server/api/context.go
, contains functions for setting and getting the connection in the request context.
Methods
SetContextConn
This method takes a context and a net.Conn as input and stores the connection in the request context. It returns the updated context.
GetContextConn
This method takes an HTTP request as input and retrieves the stored connection from the request context. It returns the net.Conn if found, otherwise it returns nil.
package api
import (
"context"
"net"
"net/http"
)
type contextKey int
const (
httpConnContextKey contextKey = iota
sessionContextKey
)
// SetContextConn stores the connection in the request context.
func SetContextConn(ctx context.Context, c net.Conn) context.Context {
return context.WithValue(ctx, httpConnContextKey, c)
}
// GetContextConn gets the stored connection from the request context.
func GetContextConn(r *http.Request) net.Conn {
value := r.Context().Value(httpConnContextKey)
if value == nil {
return nil
}
return value.(net.Conn)
}