加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Go-restful Usage

发布时间:2020-12-16 18:29:48 所属栏目:大数据 来源:网络整理
导读:1.前言 Go 语言是一种表达能力非常强大的语言。目前有一个Golang实现的restful webservice 包,go-restful使用起来很简单。 2.Demo 例子实现了一个查询操作,更详细的Demo见这里:https://github.com/emicklei/go-restful/blob/master/examples/restful-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 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的对接,功能很完善。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读