前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >我二次封装了一下字节跳动的 hertz 框架

我二次封装了一下字节跳动的 hertz 框架

作者头像
老麦
发布2024-03-22 13:57:11
830
发布2024-03-22 13:57:11
举报
文章被收录于专栏:Go与云原生Go与云原生

大家好, 我是 老麦, 一个运维老兵, 现在专注于 Golang,DevOps,云原生基础设施建设。

我二次封装了一下字节跳动的 hertz 框架

  1. a gin webserver which bases on cloudwebgo/hertz
  2. inspired by cobra for the RouterGroup management

项目地址: https://github.com/go-jarvis/hertzer

1. Usage

go to example/demo

代码语言:javascript
复制
go get -u github.com/go-jarvis/hertzer

2. Server

代码语言:javascript
复制
func main() {

// define a server
 s := &hertzer.Server{
  Listen: ":8081",
 }

// set server options, sam eas hertz
 s.WithOptions(
  server.WithBasePath("/api"),
  server.WithIdleTimeout(10),
 )

// add middlewares, same as the hertz
 s.Use(prefunc(), postfunc())

// handle a router handler
 s.Handle(&Ping{})

// Run server
 if err := s.Run(); err != nil {
  panic(err)
 }
}

3. Router Handler

Main Router HandlerFunc

代码语言:javascript
复制
type Ping struct {
 httpx.MethodPost `route:"/ping/:name"` // define method and path

// define the body
 Name      string  `path:"name"`
 Age       int     `query:"age"`
 AuthToken string  `header:"AuthToken"`
 Address   Address `json:"address"`
 Score     int     `json:"score" form:"score"`
}


// Handle method must exists.
// reqeust data will be binded into p automaticly.
// it can be used directly.
func (p *Ping) Handle(ctx context.Context, arc *app.RequestContext) (any, error) {

 fmt.Println(p.Address)

 ret := resp.NewStatusResponse(consts.StatusAccepted, *p)
 return ret, nil
}

So that, the default handler will be like:

代码语言:javascript
复制
// r.Handle(httpMethod, relativePath string, handlers ...app.HandlerFunc)
r.Handle("POST","/ping/:name", handler)

3.1. Hanlder's HandlerFuncChain

Add the PreHandlers and PostHandlers to combine the HandlerFunc Chain. NOTE: PreHandlers and PostHandlers as optional.

代码语言:javascript
复制
func (Ping) PreHandlers() []app.HandlerFunc {
 return []app.HandlerFunc{
  prefunc(),
 }
}

func (Ping) PostHandlers() []app.HandlerFunc {
 return []app.HandlerFunc{
  postfunc(),
 }
}

The Registered Router will be like

代码语言:javascript
复制
// r.Handle(httpMethod, relativePath string, handlers ...app.HandlerFunc)
r.Handle("POST","/ping/:name", [pre...,] handler, [post...])

3.2 RouterGroup

As metioned before, the RouterGroups like the carriages of a train. They are not only mounted one by one, and but also can be mounted to any RouterGroup.

NOTE: The Mounted Ring is forbidden. And Directed Acyclic Graph(DAG) of RouterGroups are required.

  1. Using v1:=hertzer.NewRouterGroup(v1) to create a new RouterGroup
  2. Using v2.AddGroup(v2) to add children RouterGroup(s).
代码语言:javascript
复制
// define a server
 s := &hertzer.Server{
  Listen: ":8081",
 }

// define Router Groups
 v1 := hertzer.NewRouterGroup("/v1")
 v1.Handle(&Ping{})

 v2 := hertzer.NewRouterGroup("/v2")

// mount children RouterGroup(s)
 s.AddGroup(v1)
 v1.AddGroup(v2)
 s.AddGroup(v2)

4. Response and Error

By default,

代码语言:javascript
复制
func (p *Ping) Handle(...) (result any, err error) {}

Typically, the response will be

  1. if the error is nil:
    • status code = 200 // http.StatusOK
    • the data is "result"
  2. if the error is not nil:
    • status code = 500 // http.StatusInternalServerError
    • the data is "err.Error()"

the 3rd response is special, Router Binding error. + status code = 400 // StatusBadRequest + the data is actual value of binding error

4.1. Status Reponse

However, you may use resp.NewStatusResponse to set the HTTP Status Code whatever you need.

代码语言:javascript
复制
// define
func NewStatusResponse(code int, meta interface{}) StatusResponse {
 return &statusResponse{
  code: code,
  meta: meta,
 }
}

// usage
ret := resp.NewStatusResponse(consts.StatusBadGateway, *p)
return ret, nil

4.2. Status Error

By the way, you can use errors.New to create a status error.

代码语言:javascript
复制
// define
func New(err error, meta any) *StatusError {
 return &StatusError{
  Err:  err,
  Meta: meta,
  Message: "",
 }
}

// usage
serr := errors.New(err, *p)
serr = serr.SetMessage("Error Message")

By default the Message will be the HTTP Status Message/Define if you don't SetMessage

本文参与?腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-03-14,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 熊猫云原生Go 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Usage
  • 2. Server
  • 3. Router Handler
    • 3.1. Hanlder's HandlerFuncChain
      • 3.2 RouterGroup
      • 4. Response and Error
        • 4.1. Status Reponse
          • 4.2. Status Error
          相关产品与服务
          CODING DevOps
          CODING DevOps 一站式研发管理平台,包括代码托管、项目管理、测试管理、持续集成、制品库等多款产品和服务,涵盖软件开发从构想到交付的一切所需,使研发团队在云端高效协同,实践敏捷开发与 DevOps,提升软件交付质量与速度。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
          http://www.vxiaotou.com