REST(Representational State Transfer,表現(xiàn)層狀態(tài)轉(zhuǎn)化)是近幾年使用較廣泛的分布式結(jié)點(diǎn)間同步通信的實(shí)現(xiàn)方式。REST原則描述網(wǎng)絡(luò)中client-server的一種交互形式,即用URL定位資源,用HTTP方法描述操作的交互形式。如果CS之間交互的網(wǎng)絡(luò)接口滿足REST風(fēng)格,則稱為RESTful API。以下是 理解RESTful架構(gòu) 總結(jié)的REST原則:
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供安陽(yáng)縣網(wǎng)站建設(shè)、安陽(yáng)縣做網(wǎng)站、安陽(yáng)縣網(wǎng)站設(shè)計(jì)、安陽(yáng)縣網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、安陽(yáng)縣企業(yè)網(wǎng)站模板建站服務(wù),十多年安陽(yáng)縣做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
為什么要設(shè)計(jì)RESTful的API,個(gè)人理解原因在于:用HTTP的操作統(tǒng)一數(shù)據(jù)操作接口,限制URL為資源,即每次請(qǐng)求對(duì)應(yīng)某種資源的某種操作,這種 無(wú)狀態(tài)的設(shè)計(jì)可以實(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三個(gè)重要數(shù)據(jù)結(jié)構(gòu)。
最簡(jiǎn)單的使用實(shí)例,向WebService注冊(cè)路由,將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)庫(kù)http的路由器ServeMux寫的,并且它通過(guò)ServeMux的路由表實(shí)現(xiàn)了Handler接口,可參考以前的這篇 HTTP協(xié)議與Go的實(shí)現(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并注冊(cè)到mux的是dispatch這個(gè)函數(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表示一個(gè)共享rootPath的服務(wù),其中rootPath通過(guò) 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 }
通過(guò)Route注冊(cè)的路由最終構(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
通過(guò)RouteBuilder構(gòu)造Route信息,Path結(jié)合了rootPath和subPath。Function是路由Handler,即處理函數(shù),它通過(guò) ws.Get(subPath).To(function) 的方式加入。Filters實(shí)現(xiàn)了個(gè)類似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包實(shí)現(xiàn)了一個(gè) ServeMux ,go-restful在這個(gè)基礎(chǔ)上封裝了多個(gè)服務(wù),如何在從container開始將路由分發(fā)給webservice,再由webservice分發(fā)給具體處理函數(shù)。這些都在 dispatch 中實(shí)現(xiàn)。
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實(shí)現(xiàn)的rest-server是在go-restful上的一層封裝。Register時(shí)只要將注冊(cè)的schema解析成routes,并注冊(cè)到webService中,Start啟動(dòng)server時(shí) container.Add(r.ws) ,同時(shí)將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注冊(cè)不同方法的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 }
實(shí)在是比較簡(jiǎn)單,就不寫了。今天好困。
遺留問(wèn)題
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。