侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

浅谈go-restful框架的使用和实现

Go  /  管理员 发布于 5年前   277

REST(Representational State Transfer,表现层状态转化)是近几年使用较广泛的分布式结点间同步通信的实现方式。REST原则描述网络中client-server的一种交互形式,即用URL定位资源,用HTTP方法描述操作的交互形式。如果CS之间交互的网络接口满足REST风格,则称为RESTful API。以下是 理解RESTful架构 总结的REST原则:

  1. 网络上的资源通过URI统一标示。
  2. 客户端和服务器之间传递,这种资源的某种表现层。表现层可以是json,文本,二进制或者图片等。
  3. 客户端通过HTTP的四个动词,对服务端资源进行操作,实现表现层状态转化。

为什么要设计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三个重要数据结构。

  1. Route 表示一条路由,包含 URL/HTTP method/输入输出类型/回调处理函数RouteFunction
  2. WebService 表示一个服务,由多个Route组成,他们共享同一个Root Path
  3. Container 表示一个服务器,由多个WebService和一个 http.ServerMux 组成,使用RouteSelector进行分发

最简单的使用实例,向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 中实现。

  1. SelectRoute根据Req在注册的WebService中选择匹配的WebService和匹配的Route。其中路由选择器默认是 CurlyRouter 。
  2. 解析pathParams,将wrap的请求和相应交给路由的处理函数处理。如果有filters定义,则链式处理。
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}

实在是比较简单,就不写了。今天好困。

遗留问题

  1. reflect在路由注册中的使用,反射与性能
  2. route select时涉及到模糊匹配 如何保证处理速度
  3. pathParams的解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    利用 Go 语言编写一个简单的 WebSocket 推送服务
    下一条:
    利用GO语言实现多人聊天室实例教程
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客