Why Context Should Be the First Parameter in Go Functions

Context must be the first parameter in Go functions to prevent accidental omission and ensure consistent cancellation and timeout propagation.

Context should be the first parameter in Go functions to ensure it is never forgotten and to allow the compiler to enforce its presence in call chains. This convention enables the compiler to detect if a context is missing and allows tools to easily trace context propagation through your codebase.

func HandleRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    // ctx is guaranteed to be present and can be used for timeouts/cancellation
    if err := process(ctx); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}