2

In the main function, I have a gorilla mux router, and a function to handle the route.

var router = mux.NewRouter()
func main() {   
    router.HandleFunc("/", ParseSlash)
    http.Handle("/", router)
    http.ListenAndServe(":8000", nil)
}

and ParseSlash looks like

const slash = `<h1>Login</h1>
<form method="post" action="/login">
  <label for="name">User name</label>
  <input type="text" id="name" name="name">
  <label for="password">Password</label>
  <input type="password" id="password" name="password">
  <button type="submit">Login</button>
</form>`

func ParseSlash(response http.ResponseWriter, request *http.Request)  {
    fmt.Fprintf(response, slash)
}

However, in main, we are not calling the function as ParseSlash(), but ParseSlash inside router.HandleFunc(). Where do the function get the parameters from, if we are not providing explicitely? What is this way of calling a function termed as?

Thank you.

2 Answers 2

11

You are not "calling" the function from main, you are providing it as a argument to HandleFunc, registering it to be called for the path "/" in the mux.Router. This pattern of providing a function to be called later is typically known as a "callback".

Your ParseSlash function is of the type http.HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

Your function is eventually called by the http.Server via its ServeHTTP method (here, via the mux.Router), passing the arguments shown. When the function is called, the http.ResponseWriter and *http.Request arguments are for the individual http request being handled.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition, the "function without brackets" as you named it, is called a callback and is a common technique, for which you can find lots of resources online. It is very common (and imho essential) in e.g. JavaScript.
2

It is a simple callback. You need that, when you want to call some function in the future, but now you don't have enough information to do it. Look - http.ListenAndServe create a server and waits for client.

You cannot call function ParseSlash, because it make sense after client will connect and will send address "/". When it happened router would have enough information to call your code back with arguments http.ResponseWriter and *http.Request.

Now you should learn how closures works - https://tour.golang.org/moretypes/25 . And you will done let's return back to http server https://www.nicolasmerouze.com/middlewares-golang-best-practices-examples/ .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.