Go-restful Usage

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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的對接,功能很完善。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.