国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Golang > 正文

淺談go-restful框架的使用和實(shí)現(xiàn)

2020-04-01 18:57:57
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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原則:

  1. 網(wǎng)絡(luò)上的資源通過(guò)URI統(tǒng)一標(biāo)示。
  2. 客戶端和服務(wù)器之間傳遞,這種資源的某種表現(xiàn)層。表現(xiàn)層可以是json,文本,二進(jìn)制或者圖片等。
  3. 客戶端通過(guò)HTTP的四個(gè)動(dòng)詞,對(duì)服務(wù)端資源進(jìn)行操作,實(shí)現(xiàn)表現(xiàn)層狀態(tài)轉(zhuǎn)化。

為什么要設(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)。

  1. Route 表示一條路由,包含 URL/HTTP method/輸入輸出類型/回調(diào)處理函數(shù)RouteFunction
  2. WebService 表示一個(gè)服務(wù),由多個(gè)Route組成,他們共享同一個(gè)Root Path
  3. Container 表示一個(gè)服務(wù)器,由多個(gè)WebService和一個(gè) http.ServerMux 組成,使用RouteSelector進(jìn)行分發(fā)

最簡(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)。

  1. SelectRoute根據(jù)Req在注冊(cè)的WebService中選擇匹配的WebService和匹配的Route。其中路由選擇器默認(rèn)是 CurlyRouter 。
  2. 解析pathParams,將wrap的請(qǐng)求和相應(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實(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)題

  1. reflect在路由注冊(cè)中的使用,反射與性能
  2. route select時(shí)涉及到模糊匹配 如何保證處理速度
  3. pathParams的解析

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 乐平市| 张家口市| 孟津县| 锡林浩特市| 丰城市| 清原| 阿合奇县| 东乡族自治县| 甘肃省| 许昌县| 阳曲县| 内丘县| 通化县| 台山市| 英吉沙县| 盱眙县| 武城县| 临颍县| 石景山区| 福清市| 承德市| 通河县| 阿图什市| 湘潭县| 四平市| 澎湖县| 宁德市| 五家渠市| 犍为县| 祁连县| 清水河县| 杨浦区| 九江市| 浦北县| 夹江县| 清涧县| 东乡族自治县| 虎林市| 民乐县| 兴义市| 德清县|