How can I pass the parameter to a Http handler function

9,017 views
Skip to first unread message

nvcnvn

unread,
Nov 14, 2011, 9:39:35 AM11/14/11
to golang-nuts
Example:
#############################
func handler(w http.ResponseWriter, r *http.Request, mystr string) {
println(mystr);
}
func main() {
hi := "hello"
http.HandleFunc("/test", handler)
http.ListenAndServe(":8080", nil)
}
#############################

How can I pass "hi" to my handler?

chris dollin

unread,
Nov 14, 2011, 11:07:52 AM11/14/11
to nvcnvn, golang-nuts

Use a closure,

(That is, make `handler` take `hi` as an argument, then pass

func (w http.ResponseWriter, r *http.Request, mystr string) {
handler( hi, w, t ) }

to HandleFunc.)

Or make a type satisfying the Handler interface and put your
hi variable in it.

Chris

--
Chris "allusive" Dollin

Kyle Lemons

unread,
Nov 14, 2011, 11:12:36 AM11/14/11
to nvcnvn, golang-nuts
func handler(w http.ResponseWriter, r *http.Request, mystr string) {
       println(mystr);
}
func main() {
       hi := "hello"
       http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
              handler(w, r, hi)
       })
       http.ListenAndServe(":8080", nil)
}


Keep in mind, updating "hi" is not advisable after this, because it will be accessed concurrently from other goroutines, so you'd need a lock or some other scheme if you were going to do so.

rugwir...@gmail.com

unread,
Apr 5, 2018, 1:26:19 PM4/5/18
to golang-nuts
This thread saved me many hours of my life.
Reply all
Reply to author
Forward
0 new messages