如何在GO语言和Google App Engine中将*url.URL转换为字符串

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

How to convert *url.URL to string in GO, Google App Engine

问题

我想获取URL并将其转换为字符串。我有以下代码:

func getURL(w http.ResponseWriter, r *http.Request) {
    var url string = r.URL
}

我得到了这个错误:

> "无法将r.URL(类型为*url.URL)转换为字符串类型"

这个代码可以正常工作:

fmt.Fprint(w, r.URL)

但是我想使用它,而不仅仅是打印它。

我应该怎么做?

英文:

I would like to get the URL and convert it to string. I have to following code:

func getURL(w http.ResponseWriter, r *http.Request) {
    var url string = r.URL
}

I get this:

> "cannot convert r.URL (type *url.URL) to type string"

This is working well:

fmt.Fprint(w,r.URL)

But I would like to use it, not just print it.

What should I do?

答案1

得分: 44

The url.URL type has a .String() method.

Try this.

func getURL(w http.ResponseWriter, r *http.Request) {
    url := r.URL.String()
}

http://golang.org/pkg/net/url/#URL.String

英文:

The url.URL type has a .String() method.

Try this.

func getURL(w http.ResponseWriter, r *http.Request) {
    url := r.URL.String()
}

http://golang.org/pkg/net/url/#URL.String

huangapple
  • 本文由 发表于 2012年12月16日 05:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/13896592.html
匿名

发表评论

匿名网友

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

确定