這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
1.前言
Go 語言是一種表達能力非常強大的語言。目前有一個Golang實現的restful webservice 包,go-restful使用起來很簡單。
2.Demo
例子實現了一個查詢操作,更詳細的Demo見這裡:https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go
package mainimport ("log""net/http"//"strconv""github.com/emicklei/go-restful""github.com/emicklei/go-restful/swagger")type User struct {Id,Name string}type UserResource struct {users map[string]User}func (u UserResource) Register(container *restful.Container) {ws := new(restful.WebService)ws.Path("/users").Doc("Manage Users").Consumes(restful.MIME_XML, restful.MIME_JSON).Produces(restful.MIME_JSON, restful.MIME_XML)ws.Route(ws.GET("/{user-id}").To(u.findUser).// docsDoc("get a user").Operation("findUser").Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")).Writes(User{})) // on the responsecontainer.Add(ws)}func (u UserResource) findUser(request *restful.Request, response *restful.Response) {id := request.PathParameter("user-id")usr := u.users[id]if len(usr.Id) == 0 {response.AddHeader("Content-Type", "text/plain")response.WriteErrorString(http.StatusNotFound, "404: User could not be found.")return}response.WriteEntity(usr)}func main () {wsContainer := restful.NewContainer()userMap := map[string]User{"1":User{"1","tom"},"2":User{"2","jerry"},}u := UserResource{userMap}u.Register(wsContainer)config := swagger.Config{WebServices: wsContainer.RegisteredWebServices(), // you control what services are visibleWebServicesUrl: "http://localhost:8080",ApiPath: "/apidocs.json",// Optionally, specifiy where the UI is locatedSwaggerPath: "/apidocs/",SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"}swagger.RegisterSwaggerService(config, wsContainer)log.Printf("start listening on localhost:8080")server := &http.Server{Addr: ":8080", Handler: wsContainer}log.Fatal(server.ListenAndServe())}3.總結
Golang 中的go-restful 庫在k8s中作為apiserver的rest架構來實現,實現路由和handler的對接,功能很完善。