登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-06 19:30:28 188浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《将参数传递给 golang 中的 mux 处理函数》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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

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

以上就是《将参数传递给 golang 中的 mux 处理函数》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>