5

I'm trying to use mux and set some handlers. I have the following handler

func homePage(w http.ResponseWriter, r *http.Request) {
    // Some code
}

func main() {
    router := mux.NewRouter().StrictSlash(true)

    router.HandleFunc("/", homePage)
    log.Fatal(http.ListenAndServe(":8090", router))
}

Is there any way to pass more arguments to the handler function so that I can do more logic? I mean add an argument to homePage function called message. Something like this...

func homePage(w http.ResponseWriter, r *http.Request, message string) {
    // Do some logic with message

    // Rest of code
}

func main() {
    router := mux.NewRouter().StrictSlash(true)

    router.HandleFunc("/", homePage("hello"))
    log.Fatal(http.ListenAndServe(":8090", router))
}
MohamedSaeed
  • 455
  • 1
  • 8
  • 11
  • Does the value of the parameter you want to add change per request? Or are you looking to accept additional parameters that won't change after setting up your routes? – kingkupps Aug 29 '20 at 01:59
  • They won't change. But their values will be initiated first in the main function and then I will pass them to more than one handler. – MohamedSaeed Aug 29 '20 at 02:17

1 Answers1

13

A common technique for doing this is to return your handlers from a function that accepts any additional parameters you want like this:

package main

import (
    "net/http"
)

func homePage(msg string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Do stuff with "msg"
        w.Write([]byte(msg))
    }
}

func main() {
    http.HandleFunc("/", homePage("message"))
    http.ListenAndServe(":8090", nil)
}
kingkupps
  • 3,284
  • 2
  • 16
  • 28