淺談go-restful框架的使用和實現(xiàn)
REST(Representational State Transfer,表現(xiàn)層狀態(tài)轉(zhuǎn)化)是近幾年使用較廣泛的分布式結(jié)點間同步通信的實現(xiàn)方式。REST原則描述網(wǎng)絡(luò)中client-server的一種交互形式,即用URL定位資源,用HTTP方法描述操作的交互形式。如果CS之間交互的網(wǎng)絡(luò)接口滿足REST風(fēng)格,則稱為RESTful API。以下是 理解RESTful架構(gòu) 總結(jié)的REST原則:
- 網(wǎng)絡(luò)上的資源通過URI統(tǒng)一標(biāo)示。
- 客戶端和服務(wù)器之間傳遞,這種資源的某種表現(xiàn)層。表現(xiàn)層可以是json,文本,二進(jìn)制或者圖片等。
- 客戶端通過HTTP的四個動詞,對服務(wù)端資源進(jìn)行操作,實現(xiàn)表現(xiàn)層狀態(tài)轉(zhuǎn)化。
為什么要設(shè)計RESTful的API,個人理解原因在于:用HTTP的操作統(tǒng)一數(shù)據(jù)操作接口,限制URL為資源,即每次請求對應(yīng)某種資源的某種操作,這種 無狀態(tài)的設(shè)計可以實現(xiàn)client-server的解耦分離,保證系統(tǒng)兩端都有橫向擴(kuò)展能力。
go-restful
go-restful is a package for building REST-style Web Services using Google Go。go-restful定義了Container WebService和Route三個重要數(shù)據(jù)結(jié)構(gòu)。
- Route 表示一條路由,包含 URL/HTTP method/輸入輸出類型/回調(diào)處理函數(shù)RouteFunction
- WebService 表示一個服務(wù),由多個Route組成,他們共享同一個Root Path
- Container 表示一個服務(wù)器,由多個WebService和一個 http.ServerMux 組成,使用RouteSelector進(jìn)行分發(fā)
最簡單的使用實例,向WebService注冊路由,將WebService添加到Container中,由Container負(fù)責(zé)分發(fā)。
func main() { ws := new(restful.WebService) ws.Path("/users") ws.Route(ws.GET("/").To(u.findAllUsers). Doc("get all users"). Metadata(restfulspec.KeyOpenAPITags, tags). Writes([]User{}). Returns(200, "OK", []User{})) container := restful.NewContainer().Add(ws) http.ListenAndServe(":8080", container) }
container
container是根據(jù)標(biāo)準(zhǔn)庫http的路由器ServeMux寫的,并且它通過ServeMux的路由表實現(xiàn)了Handler接口,可參考以前的這篇 HTTP協(xié)議與Go的實現(xiàn) 。
type Container struct { webServicesLock sync.RWMutex webServices []*WebService ServeMux *http.ServeMux isRegisteredOnRoot bool containerFilters []FilterFunction doNotRecover bool // default is true recoverHandleFunc RecoverHandleFunction serviceErrorHandleFunc ServiceErrorHandleFunction router RouteSelector // default is a CurlyRouter contentEncodingEnabled bool // default is false }
func (c *Container)ServeHTTP(httpwriter http.ResponseWriter, httpRequest *http.Request) { c.ServeMux.ServeHTTP(httpwriter, httpRequest) }
往Container內(nèi)添加WebService,內(nèi)部維護(hù)的webServices不能有重復(fù)的RootPath,
func (c *Container)Add(service *WebService)*Container { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() if !c.isRegisteredOnRoot { c.isRegisteredOnRoot = c.addHandler(service, c.ServeMux) } c.webServices = append(c.webServices, service) return c }
添加到container并注冊到mux的是dispatch這個函數(shù),它負(fù)責(zé)根據(jù)不同WebService的rootPath進(jìn)行分發(fā)。
func (c *Container)addHandler(service *WebService, serveMux *http.ServeMux)bool { pattern := fixedPrefixPath(service.RootPath()) serveMux.HandleFunc(pattern, c.dispatch) }
webservice
每組webservice表示一個共享rootPath的服務(wù),其中rootPath通過 ws.Path() 設(shè)置。
type WebService struct { rootPath string pathExpr *pathExpression routes []Route produces []string consumes []string pathParameters []*Parameter filters []FilterFunction documentation string apiVersion string typeNameHandleFunc TypeNameHandleFunction dynamicRoutes bool routesLock sync.RWMutex }
通過Route注冊的路由最終構(gòu)成Route結(jié)構(gòu)體,添加到WebService的routes中。
func (w *WebService)Route(builder *RouteBuilder)*WebService { w.routesLock.Lock() defer w.routesLock.Unlock() builder.copyDefaults(w.produces, w.consumes) w.routes = append(w.routes, builder.Build()) return w }
route
通過RouteBuilder構(gòu)造Route信息,Path結(jié)合了rootPath和subPath。Function是路由Handler,即處理函數(shù),它通過 ws.Get(subPath).To(function) 的方式加入。Filters實現(xiàn)了個類似gRPC攔截器的東西,也類似go-chassis的chain。
type Route struct { Method string Produces []string Consumes []string Path string // webservice root path + described path Function RouteFunction Filters []FilterFunction If []RouteSelectionConditionFunction // cached values for dispatching relativePath string pathParts []string pathExpr *pathExpression // documentation Doc string Notes string Operation string ParameterDocs []*Parameter ResponseErrors map[int]ResponseError ReadSample, WriteSample interface{} Metadata map[string]interface{} Deprecated bool }
dispatch
server側(cè)的主要功能就是路由選擇和分發(fā)。http包實現(xiàn)了一個 ServeMux ,go-restful在這個基礎(chǔ)上封裝了多個服務(wù),如何在從container開始將路由分發(fā)給webservice,再由webservice分發(fā)給具體處理函數(shù)。這些都在 dispatch 中實現(xiàn)。
- SelectRoute根據(jù)Req在注冊的WebService中選擇匹配的WebService和匹配的Route。其中路由選擇器默認(rèn)是 CurlyRouter 。
- 解析pathParams,將wrap的請求和相應(yīng)交給路由的處理函數(shù)處理。如果有filters定義,則鏈?zhǔn)教幚怼?/li>
func (c *Container)dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) { func() { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() webService, route, err = c.router.SelectRoute( c.webServices, httpRequest) }() pathProcessor, routerProcessesPath := c.router.(PathProcessor) pathParams := pathProcessor.ExtractParameters(route, webService, httpRequest.URL.Path) wrappedRequest, wrappedResponse := route.wrapRequestResponse(writer, httpRequest, pathParams) if len(c.containerFilters)+len(webService.filters)+len(route.Filters) > 0 { chain := FilterChain{Filters: allFilters, Target: func(req *Request, resp *Response) { // handle request by route after passing all filters route.Function(wrappedRequest, wrappedResponse) }} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { route.Function(wrappedRequest, wrappedResponse) } }
go-chassis
go-chassis實現(xiàn)的rest-server是在go-restful上的一層封裝。Register時只要將注冊的schema解析成routes,并注冊到webService中,Start啟動server時 container.Add(r.ws) ,同時將container作為handler交給 http.Server , 最后開始ListenAndServe即可。
type restfulServer struct { microServiceName string container *restful.Container ws *restful.WebService opts server.Options mux sync.RWMutex exit chan chan error server *http.Server }
根據(jù)Method不同,向WebService注冊不同方法的handle,從schema讀取的routes信息包含Method,F(xiàn)unc以及PathPattern。
func (r *restfulServer)Register(schemainterface{}, options ...server.RegisterOption)(string, error) { schemaType := reflect.TypeOf(schema) schemaValue := reflect.ValueOf(schema) var schemaName string tokens := strings.Split(schemaType.String(), ".") if len(tokens) >= 1 { schemaName = tokens[len(tokens)-1] } routes, err := GetRoutes(schema) for _, route := range routes { lager.Logger.Infof("Add route path: [%s] Method: [%s] Func: [%s]. ", route.Path, route.Method, route.ResourceFuncName) method, exist := schemaType.MethodByName(route.ResourceFuncName) ... handle := func(req *restful.Request, rep *restful.Response) { c, err := handler.GetChain(common.Provider, r.opts.ChainName) inv := invocation.Invocation{ MicroServiceName: config.SelfServiceName, SourceMicroService: req.HeaderParameter(common.HeaderSourceName), Args: req, Protocol: common.ProtocolRest, SchemaID: schemaName, OperationID: method.Name, } bs := NewBaseServer(context.TODO()) bs.req = req bs.resp = rep c.Next(&inv, func(ir *invocation.InvocationResponse)error { if ir.Err != nil { return ir.Err } method.Func.Call([]reflect.Value{schemaValue, reflect.ValueOf(bs)}) if bs.resp.StatusCode() >= http.StatusBadRequest { return ... } return nil }) } switch route.Method { case http.MethodGet: r.ws.Route(r.ws.GET(route.Path).To(handle). Doc(route.ResourceFuncName). Operation(route.ResourceFuncName)) ... } } return reflect.TypeOf(schema).String(), nil }
實在是比較簡單,就不寫了。今天好困。
遺留問題
- reflect在路由注冊中的使用,反射與性能
- route select時涉及到模糊匹配 如何保證處理速度
- pathParams的解析
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Golang變量初始化/類型推斷/短聲明的問題
這篇文章主要介紹了關(guān)于Golang變量初始化/類型推斷/短聲明的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02pytorch中的transforms.ToTensor和transforms.Normalize的實現(xiàn)
本文主要介紹了pytorch中的transforms.ToTensor和transforms.Normalize的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04Golang 實現(xiàn)獲取當(dāng)前函數(shù)名稱和文件行號等操作
這篇文章主要介紹了Golang 實現(xiàn)獲取當(dāng)前函數(shù)名稱和文件行號等操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05