1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
package request
import (
"context"
"net"
"net/http"
"github.com/lxc/incus/v6/shared/api"
)
// CreateRequestor extracts the lifecycle event requestor data from an http.Request context.
func CreateRequestor(r *http.Request) *api.EventLifecycleRequestor {
ctx := r.Context()
requestor := &api.EventLifecycleRequestor{}
// Normal requestor.
val, ok := ctx.Value(CtxUsername).(string)
if ok {
requestor.Username = val
}
val, ok = ctx.Value(CtxProtocol).(string)
if ok {
requestor.Protocol = val
}
requestor.Address = r.RemoteAddr
// Forwarded requestor override.
val, ok = ctx.Value(CtxForwardedUsername).(string)
if ok {
requestor.Username = val
}
val, ok = ctx.Value(CtxForwardedProtocol).(string)
if ok {
requestor.Protocol = val
}
val, ok = ctx.Value(CtxForwardedAddress).(string)
if ok {
requestor.Address = val
}
// Strip port from address.
host, _, err := net.SplitHostPort(requestor.Address)
if err == nil {
requestor.Address = host
}
return requestor
}
// SaveConnectionInContext can be set as the ConnContext field of a http.Server to set the connection
// in the request context for later use.
func SaveConnectionInContext(ctx context.Context, connection net.Conn) context.Context {
return context.WithValue(ctx, CtxConn, connection)
}
|