1. 程式人生 > >Go-restful Usage

Go-restful Usage

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

相關推薦

Go-restful Usage

1.前言Go 語言是一種表達能力非常強大的語言。目前有一個Golang實現的restful webservice 包,go-restful使用起來很簡單。2.Demo例子實現了一個查詢操作,更詳細的Demo見這裡:https://github.com/emicklei/go-

【kubernetes/k8s原始碼分析】kube-apiserver的go-restful框架使用

go-restful框架     github: https://github.com/emicklei/go-restful 三個重要資料結構   1. 初始化   路徑pkg/kubelet/kubelet.go中函式Ne

Go Slices: usage and internals

5 January 2011 Introduction Go's slice type provides a convenient and efficient means of working with sequences

Building RESTful Web services with Go.pdf

gateway ble row emp isp coo div ren tin 下載地址:網盤下載 Initially, SOAP-based web services became more popular with XML. Then, since 2012, RES

談談Go語言的Restful介面開發

前言: 如今微服務、無伺服器架構大行其道。而API開發是這些話題的主角。 Go語言開發效率要比Java Spring要快一些,效能上比PHP高出一個數量級。尤其是Go語言在併發方便非常的優秀,是接下來值得關注的一門語言。 本人近來學習go語言,想基於Go做Web API,經過調研

Go Web:RESTful web service示例

RESTful架構的簡介 web服務的架構模式主要有2種:SOAP和REST。SOAP和REST都回答了同一個問題:如何訪問web服務。 SOAP風格的程式是功能驅動的,要藉助xml來傳遞資料,明確表示要做什麼動作,訪問什麼資源,但使用xml是非常繁瑣複雜的事情。 RESTful風格的Web服務是資源驅

Go實戰--通過gin-gonic框架搭建restful api服務(github.com/gin-gonic/gin)

users .post sage 事先 eat mas routes pac 操作mysql 生命不止,繼續 go go go !!! 先插播一條廣告,給你堅持學習golang的理由: 《2017 軟件開發薪酬調查:Go 和 Scala 是最賺錢的語言》 言歸正傳!

Consuming A RESTful API With Go

Note - For a Tutorial on how to build a RESTful API in Go click here In this tutorial, I’m going to be demonstrating how we can consume an alrea

Go實戰--通過httprouter和redis框架搭建restful api服務(github.com/julienschmidt/httprouter)

生命不止,繼續 go go go !!! httprouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or ju

關於Go語言在服務端做Restful介面和socket通訊

package main import (     "fmt"     "github.com/drone/routes"     "net/http" ) func getuser(w http.ResponseWriter, r *http.Request) {     params := r.URL.

Go實戰--實現簡單的restful api(The way to go)

生命不止,繼續 go go go !!! 今天跟大家介紹一下如何使用go建立一套restful api,我們依託於開源庫gorilla/mux。 let’s go~~ 何為RESTful API A RESTful API is an app

golang restful 框架之 go-swagger

restful 是這些年的高頻詞彙了,各大網際網路公司也都紛紛推出了自己的 restful api,其實 restful 和 thrift,grpc 類似,就是一種協議,但是這種協議有點特殊的就是使用 http 介面,返回的物件一般是 json 格式,這樣有個好

polaris: 一個用go實現的支援restful的web框架

介紹 polaris是一個用go實現的支援restful的web框架,主要參考tornado進行設計。 雖然在go裡面搭建一個http server非常的簡單,這裡強烈推薦gorilla,但並沒有很好的對restful模型進行支援。考察了很多開源實現,我決定還是重新造

Go語言實現複雜Restful Api

章節 程式執行結果 什麼是Restful Api? go 實現複雜 Restful Api 感想 0.程式執行結果 程式執行結果 1.什麼是Restful Api 2. go 實現複雜 Restful Api 2.1 go http server 端程

Go 一鍵生成 後端 restful api

not order .com ted tint web com restfu pda 一鍵生成 後端 restful api 說明 主要用這個庫 gitee.com/konyshe/gogo, 詳情可以去查看說明文件。 只要連接好數據庫表,不用 數據庫的 models文件

RESTful API 設計指南

head 簡單 option eat set 取出 tro 其他 first   網絡應用程序,分為前端和後端兩個部分。當前的發展趨勢,就是前端設備層出不窮(手機、平板、桌面電腦、其他專用設備……)。   因此,必須有一種統一的機制,方便不同的前端設備與後端進行通信。這

go 自己封的postgresql操作包

rep make query res urn mod .exe errors exe 1 package myDB 2 3 import ( 4 "database/sql" 5 "errors" 6 7 _ "g

Yii2 Restful Api 401

原因 數據 app -s style font code ont ram 采用Yii2 Restful Api方式為APP提供數據,默認你已經做好了所有的編碼和配置工作。采用Postman測試接口: 出現這個畫面的一個可能原因是:access_token的寫法有誤,如果你

go-005-變量

整數 func 基礎 字型 開始 import open spl 註意 概述   變量來源於數學,是計算機語言中能儲存計算結果或能表示值抽象概念。變量可以通過變量名訪問。   Go 語言變量名由字母、數字、下劃線組成,其中首個字母不能為數字。   聲明變量的一般形式是

GO中常用包筆記 bytes(四)

g 學習筆記 bytes包Package bytes對字節數組進行操作的包。功能和strings包相似.bytes包提供的功能有:和另一個字節數組切片的關系(逐字節比較大小,是否相等/相似,是否包含/包含次數,位置搜索,是否是前綴後綴)2.字節數組切片和字符串的關系(字符串中是否含有字節數組所包含的rune,