go - 将参数传递给 golang 中的 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(":8090", router))
}
有什么方法可以将更多参数传递给处理程序函数,以便我可以执行更多逻辑?我的意思是向 homePage 函数添加一个名为 message 的参数。像这样的东西...
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)
}

关于go - 将参数传递给 golang 中的 mux 处理程序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63642568/

相关文章:

go - 无法在 '/find/{id}' 下触发 API 端点执行

arrays - 解析 JSON 对象的 JSON 数组?

mongodb - 在 Golang 的 mongodb 中插入结构

image-processing - 从通过混合一堆图像创建的视频中提取帧正在改变帧的完整性

go - 如何使用 Gorilla Mux 进行 URL 匹配?

gorilla mux 路由器处理程序

http - golang 接受 gzip 后的数据

go - 使用 goroutine 运行 cmd.Wait() 时的错误处理

go - 在函数调用上定义 golang 结构的成本

map - golang map 打印乱序