如何在go-restful中绑定一个处理程序?

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

How to bind a handler in go-restful?

问题

Go-restful是一个很好且易于使用的Go RESTful风格框架,但是我对其中的一些内容有疑问(这只是一段代码):


func main() {
    service := new(restful.WebService)

    service.Route(
        service.GET("/{user-id}").To(FindUser).
        Returns(200, "hello", noMessageValue).
        Returns(500, "internal error", noMessageValue))
    restful.Add(service)
    http.ListenAndServe(":8080", nil)
}

这段代码可以正常工作。请注意最后一行的http.ListenAndServe(":8080", nil),它没有向ListenAndServe方法传递任何处理程序(而是传递了一个nil值),只传递了端口字符串。有人知道go-restful是如何实现处理程序绑定的吗?

英文:

Go-restful is a good and easy to use Go RESTful style framework, but here is something i am wondering about (this is just a piece of code):


func main() {
    service := new(restful.WebService)

    service.Route(
	service.GET("/{user-id}").To(FindUser).
	Returns(200, "hello", noMessageValue).
	Returns(500, "internal error", noMessageValue))
    restful.Add(service)
    http.ListenAndServe(":8080", nil)
} 

This code can work well. Notice the last line http.ListenAndServe(":8080", nil), it does not pass any handler to the ListenAndServe method (it passes a nil value instead), just the port string. Does anyone know how go-restful implements handler binding ?

答案1

得分: 0

在Go语言中,将nil作为处理程序传递是一种常见的做法。正如规范所说

> 处理程序通常为nil,此时将使用DefaultServeMux。

DefaultServeMux只是http包中的一个方便的全局变量。因此,go-restful默认情况下使用它

英文:

Passing nil as a handler is a common practice in Go. As the specs say,

> Handler is typically nil, in which case the DefaultServeMux is used.

DefaultServeMux is just a convenience global variable in http. So, go-restful just uses it by default.

huangapple
  • 本文由 发表于 2017年3月27日 14:17:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/43039131.html
匿名

发表评论

匿名网友

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

确定