go - 将 "net/http"上的 *Request 传递给 Golang 函数

标签 go

是否可以将请求值传递给另一个函数?

import "net/http"

func main() {
   http.HandleFunc("saySomething", Say)
}

func Say(responseW http.ResponseWriter, request *http.Request) {
   name := getName(request) // passing request value to another function
}

func getName(request someType) string {
   request.ParseForm()
   return request.Form.Get("name")
}

最佳答案

是的,你可以,因为 request 是一个常规变量。 它通过指针传递,因此如果您在 getName 中更改 request,它也会在 Say 中更改。

package main

import "net/http"

func main() {
    http.HandleFunc("saySomething", Say)
}

func Say(responseW http.ResponseWriter, request *http.Request) {
    name := getName(request) // passing request value to another function
    println(name)
}

func getName(request *http.Request) string {
    request.ParseForm()
    return request.Form.Get("name")
}

查看 Golang 之旅 https://tour.golang.org/moretypes/1

关于go - 将 "net/http"上的 *Request 传递给 Golang 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588674/

相关文章:

linux - crontab 不会运行 go/golang 程序

xml - 具有相同标签的 Golang XML 创建

go - 无法在 Golang 中的 GET 请求的 header 中传递 Bearer token

VS 代码中的 Go linter 不适用于跨多个文件的包?

Go-yaml control characters are not allowed 错误

json - 嵌套映射返回 json array[]

go-fuse 打开文件

go - 预缓存 Golang 模板或更有效的方法

go - Go 中缓冲 channel 和非缓冲 channel 之间的测距有什么区别?

go - K8s运算符(operator)监听具体配置图