如何在Go中从URL中获取值?

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

How to retrieve values from the URL in Go?

问题

例如,如果网站是https://www.example.com/signup?campaign='new_york',我想要提取出campaign的值,即'new_york'。谢谢!

英文:

For example if the website is https://www.example.com/signup?campaign='new_york', I would like to strip out the value of campaign, 'new_york'. Thanks!

答案1

得分: 5

你应该使用以下代码来获取查询参数:

campaign := r.URL.Query().Get("campaign")
英文:

You should find the query parameters by using this

campaign := r.URL.Query().Get("campaign")

答案2

得分: 2

你应该使用以下代码来获取查询字符串的值:

http.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) {
    q := r.URL.Query()
    campaign := q.Get("campaign")
    fmt.Println("campaign =>", campaign)
})
http.ListenAndServe(":8000", nil)

这段代码会在监听端口8000上启动一个HTTP服务器,并在"/signup"路径上处理请求。当有请求到达时,它会从请求的URL中获取查询字符串,并将名为"campaign"的参数值打印出来。

英文:

You should get the query string value by this code:

http.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	campaign := q.Get("campaign")
	fmt.Println("campaign =>", campaign)
})
http.ListenAndServe(":8000", nil)

huangapple
  • 本文由 发表于 2022年7月22日 19:20:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/73079531.html
匿名

发表评论

匿名网友

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

确定