将“net/http”中的*Request传递给Golang函数。

huangapple go评论82阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年6月16日 19:55:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/44588674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定