Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将参数传递给golang中的mux处理程序函数_Go_Mux - Fatal编程技术网

将参数传递给golang中的mux处理程序函数

将参数传递给golang中的mux处理程序函数,go,mux,Go,Mux,我正在尝试使用mux并设置一些处理程序。我有以下处理程序 func homePage(w http.ResponseWriter, r *http.Request) { // Some code } func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", homePage) log.Fatal(http.ListenAndServe(&

我正在尝试使用mux并设置一些处理程序。我有以下处理程序

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))
}
有没有办法向处理函数传递更多的参数,以便我可以执行更多的逻辑?我的意思是在
主页
函数中添加一个名为
消息
的参数。像这样的

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))
}

执行此操作的一种常见技术是从接受以下任何附加参数的函数返回处理程序:

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)
}

是否要为每个请求添加更改的参数值?或者,您是否希望接受设置路线后不会更改的其他参数?它们不会更改。但是它们的值将首先在主函数中启动,然后我将把它们传递给多个处理程序。