英文:
Passing *Request on "net/http" to function Golang
问题
能否将请求值传递给另一个函数?
import "net/http"
func main() {
http.HandleFunc("saySomething", Say)
}
func Say(responseW http.ResponseWriter, request *http.Request) {
name := getName(request) // 将请求值传递给另一个函数
}
func getName(request someType) string {
request.ParseForm()
return request.Form.Get("name")
}
英文:
Is it possible to pass Request value to another function?
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")
}
答案1
得分: 3
是的,你可以这样做,因为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) // 将 request 的值传递给另一个函数
println(name)
}
func getName(request *http.Request) string {
request.ParseForm()
return request.Form.Get("name")
}
请参考 Golang 教程 https://tour.golang.org/moretypes/1
英文:
Yes, you can 'cause request
is a regular variable.
It's passed by pointer, so if you will change request
in getName
it will change in Say
too.
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")
}
See Golang tour https://tour.golang.org/moretypes/1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论