1.前言
Go 语言是一种表达能力非常强大的语言。目前有一个Golang实现的restful webservice 包,go-restful使用起来很简单。
2.Demo
例子实现了一个查询操作,更详细的Demo见这里:https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go
package main import ( "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). // docs Doc("get a user"). Operation("findUser"). Param(ws.PathParameter("user-id","identifier of the user").DataType("string")). Writes(User{})) // on the response container.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 visible WebServicesUrl: "http://localhost:8080",ApiPath: "/apidocs.json",// Optionally,specifiy where the UI is located SwaggerPath: "/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的对接,功能很完善。
原文链接:https://www.f2er.com/go/189589.html