当前位置: 首页 > 工具软件 > go-restful > 使用案例 >

go-restful ——kubernetes使用的restful框架

方恺
2023-12-01

阅读kubernetes apiserver源码时,发现使用了go-restful,简单学习了下。主要内容来自:https://godoc.org/github.com/emicklei/go-restful

 

go-restful是go语言写的一个restful框架,里边几个概念之间的关系大概如下:

Container包含WebService,WebService包含Route,Route会把不同的路径和处理函数进行绑定。

不指定Container的情况下,会使用框架默认的container。

执行如下命令安装该框架

go get -d github.com/emicklei/go-restful

简单的示例代码,采用默认的container

package main
  
import "github.com/emicklei/go-restful"
import "net/http"
import "io"

func main() {
        ws := new(restful.WebService)
        ws.Path("/users").Consumes(restful.MIME_JSON, restful.MIME_XML).Produces(restful.MIME_JSON, restful.MIME_XML)
        ws.Route(ws.GET("/{user-id}").To(findUser))

        restful.Add(ws)

        http.ListenAndServe(":8090", nil)
}

func findUser(request *restful.Request, response *restful.Response) {
        io.WriteString(response, "test")
}

一个自定义Container的例子

package main
 
import "github.com/emicklei/go-restful"
import "net/http"
import "io"

func main() {
    //构造一个新的container
	container := restful.NewContainer()

        ws := new(restful.WebService)
        ws.Path("/users").Consumes(restful.MIME_JSON, restful.MIME_XML).Produces(restful.MIME_JSON, restful.MIME_XML)
        ws.Route(ws.GET("/{user-id}").To(findUser))

	container.Add(ws)

	server := &http.Server{Addr : ":9010", Handler : container}


        server.ListenAndServe()
}

func findUser(request *restful.Request, response *restful.Response) {
        io.WriteString(response, "test")
}

另外,container和WebService还可以添加各种Filter,用以对request和response进行处理,有点类似django中的filter

package main
 
import "github.com/emicklei/go-restful"
import "net/http"
import "io"
import "log"

func main() {
	container := restful.NewContainer()

        ws := new(restful.WebService)
        ws.Path("/users").Consumes(restful.MIME_JSON, restful.MIME_XML).Produces(restful.MIME_JSON, restful.MIME_XML)
        ws.Route(ws.GET("/{user-id}").To(findUser))

	container.Add(ws)
	container.Filter(testFilter)

	server := &http.Server{Addr : ":9010", Handler : container}


        server.ListenAndServe()
}

func findUser(request *restful.Request, response *restful.Response) {
        io.WriteString(response, "test")
}

func testFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
    log.Printf("[global-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL)
    chain.ProcessFilter(req, resp)
}

 

 类似资料: