gin icon indicating copy to clipboard operation
gin copied to clipboard

Is Gin Context violating the golang context styleguide?

Open xr opened this issue 6 months ago • 3 comments

Hey guys,

We're having some discussions regarding whether or not Gin Context violates the Go context style guide. I'd like to hear your thoughts on this.

According to the Go style guide (reference: Go Style Guide on Custom Contexts), it clearly states:

Do not create custom context types or use interfaces other than context.Context in function signatures. There are no exceptions to this rule.

However, in the case of Gin's HandlerFunc, it passes a custom *Context type.

Even though the Gin Context implements all the methods of the context.Context interface,

Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key any) any

as shown here

We still need to interpret the Go style guide. There seem to be two possible views on this:

  1. Gin's Context is acceptable: Since it implements the context.Context interface, it can be considered valid, and thus doesn't violate the style guide. Similarly, we could create other types like this:

    type interface CustomContext {
        context.Context
        // ...additional APIs that we need
    }
    
  2. Strict compliance: To adhere to the Go style guide strictly, we should always pass context.Context directly in function signatures. In this case, the design would need to change to separate the Context from custom APIs. For example, the function signature could be:

    type HandlerFunc func(ctx context.Context, api CustomAPIs)
    

What do you guys think?

xr avatar Aug 26 '24 12:08 xr