之前一直使用使用beego和原生的http来实现http接口,其中beego在路由上也提供了灵活的注册方式,但是最近在看kubernetes源码的时候发现内部使用的是 go-restful实现的,好奇之下看了下其官网。当然大部分还是在route上处理,但是使用起来感觉更加灵活直接,同时提供了很多新的特性。关键实现了类似java中swagger等功能。
以下例子作为初步尝试,后续在项目在逐步使用
package main
import (
"github.com/emicklei/go-restful"
"github.com/emicklei/go-restful-swagger12"
"io"
"log"
"net/http"
)
func main(){
wsContainer := restful.NewContainer()
// 跨域过滤器
cors := restful.CrossOriginResourceSharing{
ExposeHeaders: []string{"X-My-Header"},
AllowedHeaders: []string{"Content-Type", "Accept"},
AllowedMethods: []string{"GET", "POST"},
CookiesAllowed: false,
Container: wsContainer}
wsContainer.Filter(cors.Filter)
// Add container filter to respond to OPTIONS
wsContainer.Filter(wsContainer.OPTIONSFilter)
config := swagger.Config{
WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible
WebServicesUrl: "http://localhost:8080",
ApiPath: "/apidocs.json",
ApiVersion: "V1.0",
// Optionally, specify where the UI is located
SwaggerPath: "/apidocs/",
SwaggerFilePath: "D:/gowork/src/doublegao/experiment/restful/dist"}
swagger.RegisterSwaggerService(config, wsContainer)
//swagger.InstallSwaggerService(config)
u := UserResource{}
u.RegisterTo(wsContainer)
log.Print("start listening on localhost:8080")
server := &http.Server{Addr: ":8080", Handler: wsContainer}
defer server.Close()
log.Fatal(server.ListenAndServe())
}
type UserResource struct{}
func (u UserResource) RegisterTo(container *restful.Container) {
ws := new(restful.WebService)
//设置匹配的schema和路径
ws.Path("/user").Consumes("*/*").Produces("*/*")
//设置不同method对应的方法,参数以及参数描述和类型
//参数:分为路径上的参数,query层面的参数,Header中的参数
ws.Route(ws.GET("/{id}").
To(u.result).
Doc("方法描述:获取用户").
Param(ws.PathParameter("id", "参数描述:用户ID").DataType("string")).
Param(ws.QueryParameter("name", "用户名称").DataType("string")).
Param(ws.HeaderParameter("token", "访问令牌").DataType("string")).
Do(returns200, returns500))
ws.Route(ws.POST("").To(u.result))
ws.Route(ws.PUT("/{id}").To(u.result))
ws.Route(ws.DELETE("/{id}").To(u.result))
container.Add(ws)
}
func (UserResource) SwaggerDoc() map[string]string {
return map[string]string{
"": "Address doc",//空表示结构本省的描述
"country": "Country doc",
"postcode": "PostCode doc",
}
}
func (u UserResource) result(request *restful.Request, response *restful.Response) {
io.WriteString(response.ResponseWriter, "this would be a normal response")
}
func returns200(b *restful.RouteBuilder) {
b.Returns(http.StatusOK, "OK", "success")
}
func returns500(b *restful.RouteBuilder) {
b.Returns(http.StatusInternalServerError, "Bummer, something went wrong", nil)
}