I am fairly new to go. SignInHandler
expect a parameter of type *gin.Context
, but this is not explicitly passed during function call authHandler.SignInHandler
. Is there some sort of implicit passing or special case for context, I am not sure.
main.go
package main
var authHandler *handlers.AuthHandler
func init() {
ctx := context.Background()
authHandler = &handlers.AuthHandler{}
}
func main() {
router := gin.Default()
router.POST("/signin", authHandler.SignInHandler)
}
auth.go
type AuthHandler struct{}
func (handler *AuthHandler) SignInHandler(c *gin.Context) {
}
CodePudding user response:
No, there's nothing special in Context
argument treatment. It's argument as any other.
router.POST("/signin", authHandler.SignInHandler)
is not authHandler.SignInHandler
function call (note there are no ()
at the end). Instead it is passing the function as an argument of HandlerFunc
type to router.POST()
for later invocation (when handling route).
When server is handling request for that route; handler function will be run (by gin
) and under the hood it will indeed be called with the Context
argument as usual. That Context
will be provided by caller (usually middleware or http server).
See small demonstration in playground that shows this concept without the complexity of gin codebase.
CodePudding user response:
The function doesn't need a parameter in your example, because that code doesn't explicitly call the function. Function calls happen with the calling syntax, beginning with (
, ending with )
, with arguments (if any) in between.
Functions are first class values in Go, so you can reference them without calling them. For example:
func myFunc() {
fmt.Println("Hello")
}
func main() {
fmt.Println("- Beginning")
// Assign the function to a variable.
var someFuncVar = myFunc
fmt.Println("- Middle")
// Now call the function variable.
someFuncVar()
fmt.Println("- End")
}
Outputs:
- Beginning
- Middle
Hello
- End
authHandler.SignInHandler
is technically called a "method value" (defined here), which is a slightly more advanced version of this. By referencing the method name (SignInHandler
) through an instance (authHandler
), you get a function value which is bound to that particular instance.
Here's a more formal definition from the language spec:
If the expression x has static type T and M is in the method set of type T, x.M is called a method value. The method value x.M is a function value that is callable with the same arguments as a method call of x.M. The expression x is evaluated and saved during the evaluation of the method value; the saved copy is then used as the receiver in any calls, which may be executed later.