日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

協同開發巧用gitignore中間件避免網絡請求攜帶登錄信息_Golang

作者:王中陽Go ? 更新時間: 2022-08-14 編程語言

協同開發時本地測試

昨天的文章中提到了Go如何優雅的進行本地測試,今天分享一下:在多人協同開發中,如果大家都進行本地測試可能會出現的問題。

最大的問題就是git合并的問題,大家都改這個test文件,就會導致有沖突。

我們可以通過把test文件加到.gitignore中來解決這個問題。

比如,我的測試文件所在目錄是:app/system/script/test.go。 我就在.gitignore中添加:

app/system/script/test.go

這樣我們就不用浪費時間在解決git沖突上了。

GoFrame如何優雅的獲得方法名

今天又發現一個優雅的記錄錯誤日志的神器:runtime.Caller(0)

我們可以通過這個命令動態獲取對應的方法,從而靈活的記錄錯誤日志,方便跟蹤定位問題。

示例如下:

shared.ApiLog()中第三個參數就是動態獲取的方法名。

//上下架
func (s *goodsService) Shelves(req *goods_unify.DoShelvesReq, r *ghttp.Request) (err error) {
   defer func() {
      if err != nil {
         funcName, _, _, _ := runtime.Caller(0)
         shared.ApiLog(r, "error/client_server_goods", runtime.FuncForPC(funcName).Name(), err.Error())
      }
   }()
   err = service.GoodsUnify.DoShelves(r.Context(), req)
   if err != nil {
      return
   }
   return
}

巧用中間件

比如在登錄之后將登錄信息寫到上下文中,避免每次請求都攜帶登錄信息。

中間件在登錄之后設置關鍵信息到context上下文中

package middileware
const (
   CtxAppKey         = "AK"
   CtxAppID          = "app_id"
   CtxChannel        = "channel_id"
)
var Middleware = middlewareShared{}
type middlewareShared struct {
}
func (s *middlewareShared) Sign(r *ghttp.Request) {
   code = checkSignV2(r)
   r.Middleware.Next()
}
func checkSignV2(r *ghttp.Request) (code tools.Code) {
   code, appKey, applicationInfo, sign, parmas := getSignv2Params(r)
   if 1 != code.Code {
      return
   }
   bodyBytes, err := ioutil.ReadAll(r.Request.Body)
   if nil != err {
      code = code.UnKnow()
      return
   }
   r.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // 關鍵點
   signRight, signParam := createSignV2(applicationInfo.Data.SecretKey, parmas, string(bodyBytes))
   if signRight != sign {
      code = code.SignErr("算法錯誤")
      return
   }
   r.SetParam("appKey", appKey)
   r.SetParam("appId", applicationInfo.Data.Id)
   r.SetCtxVar(CtxAppID, applicationInfo.Data.Id)
   r.SetCtxVar(CtxChannel, applicationInfo.Data.ChannelId)
   return
}

業務邏輯直接通過context直接取值

通過r.Context().Value()獲取數據:

//校驗請求方權限
func checkLevel(r *ghttp.Request) (err error) {
   if gconv.Int(r.Context().Value(middileware.CtxChannel)) !=10 {
      err = errors.New("沒有權限")
      return
   }
   return
}

case when

當需要批量更新數據庫時,case when是個不錯的選擇,我再深入了解一下用法,后面單獨出一篇介紹 case when的文章。

總結

這篇文章總結了在協同開發中,可以把我們的調試文件添加到gitignore中,避免和其他同時因為調試文件而沖突,節省解決沖突的時間。

通過GoFrame的runtime.Caller(0)獲取方法名。

巧用中間件,避免請求中攜帶登錄信息。

原文鏈接:https://juejin.cn/post/7111695942681657381

欄目分類
最近更新