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/

相关文章:

google-chrome - 如何使用 chromedp 获取 HTTP 响应主体?

go - 创建可执行文件后获取当前文件名

Gorilla mux,计算所有传入请求

http - 动态路由的文件服务器目录

go - 如何在go中添加时区以秒为单位获取时间

python - 交互式 CLI 包 - 复选框和选择

go - 去测试错误-没有测试文件-GOPATH错误

Go 和 Gorilla Mux NotFoundHandler 不工作

generics - 使用泛型的通用 MUX 和 DEMUX

sql - 为什么我的代码错误(mssql : Violation of PRIMARY KEY constraint 'PK_SMSBlast2' . 无法在对象 'dbo.SMSBlast2' 中插入重复键)?