在单值上下文中使用多值函数url.Parse() (net/url)

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

multiple-value url.Parse() in single-value context (net/url)

问题

我正在尝试在Go语言中构建一个简单的路由器。

据我了解,url.Parse函数返回一个错误和解析后的URL,尽管我在赋值语句中包含了这两个,但我仍然得到了这个问题标题中的错误。

func (router *Router) Get(urlString string, callback func(Res, Req)) {
    parsedUrl, err := url.Parse(urlString)

    router.Methods["GET"][parsedUrl] = callback
}
英文:

I am trying to build a simple router in Go.

As I understand it url.Parse returns both an error and the parsed url, despite including both these in the assignment I am still getting the error in the title of this question

func (router *Router) Get(urlString string, callback func(Res, Req)) {
	parsedUrl, err := *url.Parse(urlString)

	router.Methods["GET"][parsedUrl] = callback
}

答案1

得分: 2

尝试将*url.Parse(urlString)中的*删除。

func (router *Router) Get(urlString string, callback func(Res, Req)) {
    parsedUrl, err := url.Parse(urlString)

    router.Methods["GET"][parsedUrl] = callback
}

Playground

另外,由于url.Parse()函数返回一个错误,你的Get()函数应该对其进行处理(最好是返回它,但也可以记录日志、抛出异常等)。

英文:

Try removing the * in *url.Parse(urlString).

func (router *Router) Get(urlString string, callback func(Res, Req)) {
    parsedUrl, err := url.Parse(urlString)

    router.Methods["GET"][parsedUrl] = callback
}

Playground

Also, as the url.Parse() function returns an error, your Get() function should do something with it (preferably return it, but otherwise log it, panic etc.)

huangapple
  • 本文由 发表于 2015年1月10日 11:00:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/27872431.html
匿名

发表评论

匿名网友

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

确定