Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API to store Creds in net/http UNIX socket request context #9

Open
mdlayher opened this issue Apr 1, 2022 · 0 comments
Open

API to store Creds in net/http UNIX socket request context #9

mdlayher opened this issue Apr 1, 2022 · 0 comments

Comments

@mdlayher
Copy link

mdlayher commented Apr 1, 2022

After a couple of iterations, I came up with mdlayher/zedhook@333d2b6 for my HTTP server which accepts incoming requests via UNIX socket.

Would it make sense to incorporate a version of this in this package? Roughly:

package peercred

// A contextKey is an opaque structure used as a key for context.Context values.
type contextKey struct{ name string }

// ContextKey stores *Creds in a context.Context Value.
var ContextKey = &contextKey{"peercred"}

// ConnContext provides a hook to store *Creds for a UNIX socket client in the
// context for a *http.Request. Use this function with *http.Server's ConnContext field.
//
// TODO: better name?
func ConnContext(ctx context.Context, c net.Conn) context.Context {
    // Best effort; we don't know if net.Conn is *net.UnixConn.
    if creds, err := peercred.Get(c); err == nil {
        ctx = context.WithValue(ctx, ContextKey, creds)
    }
    return ctx
}

Usage:

srv := &http.Server{ConnContext: peercred.ConnContext}
func (h *handler) handle(w http.ResponseWriter, r *http.Request) {
    creds, ok := r.Context().Value(peercred.ContextKey).(*peercred.Cred)
    // If ok, use creds.
}

/cc @bradfitz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant