您好,登錄后才能下訂單哦!
REST(Representational State Transfer,表現層狀態轉化)是近幾年使用較廣泛的分布式結點間同步通信的實現方式。REST原則描述網絡中client-server的一種交互形式,即用URL定位資源,用HTTP方法描述操作的交互形式。如果CS之間交互的網絡接口滿足REST風格,則稱為RESTful API。以下是 理解RESTful架構 總結的REST原則:
為什么要設計RESTful的API,個人理解原因在于:用HTTP的操作統一數據操作接口,限制URL為資源,即每次請求對應某種資源的某種操作,這種 無狀態的設計可以實現client-server的解耦分離,保證系統兩端都有橫向擴展能力。
go-restful
go-restful is a package for building REST-style Web Services using Google Go。go-restful定義了Container WebService和Route三個重要數據結構。
最簡單的使用實例,向WebService注冊路由,將WebService添加到Container中,由Container負責分發。
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是根據標準庫http的路由器ServeMux寫的,并且它通過ServeMux的路由表實現了Handler接口,可參考以前的這篇 HTTP協議與Go的實現 。
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內添加WebService,內部維護的webServices不能有重復的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這個函數,它負責根據不同WebService的rootPath進行分發。
func (c *Container)addHandler(service *WebService, serveMux *http.ServeMux)bool { pattern := fixedPrefixPath(service.RootPath()) serveMux.HandleFunc(pattern, c.dispatch) }
webservice
每組webservice表示一個共享rootPath的服務,其中rootPath通過 ws.Path() 設置。
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注冊的路由最終構成Route結構體,添加到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構造Route信息,Path結合了rootPath和subPath。Function是路由Handler,即處理函數,它通過 ws.Get(subPath).To(function) 的方式加入。Filters實現了個類似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側的主要功能就是路由選擇和分發。http包實現了一個 ServeMux ,go-restful在這個基礎上封裝了多個服務,如何在從container開始將路由分發給webservice,再由webservice分發給具體處理函數。這些都在 dispatch 中實現。
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實現的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 }
根據Method不同,向WebService注冊不同方法的handle,從schema讀取的routes信息包含Method,Func以及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 }
實在是比較簡單,就不寫了。今天好困。
遺留問題
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。