Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A tutorial on the methods of migrating go-zero from enterprise projects

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the method tutorial of enterprise project migration go-zero". In the daily operation, I believe that many people have doubts about the method tutorial of enterprise project migration go-zero. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "enterprise project migration go-zero method tutorial". Next, please follow the editor to study!

Gateway service

I have made some customizations in gateway. When the end requests our backend interface, although in most cases we do not need to care about the error code, we cannot avoid that some scenarios still need to be specially handled according to the fixed error code. I have defined an error class, which is only used in gateway:

Err.go:

Package xerrimport "fmt" type CodeError struct {errCode int errMsg string} / / attribute func (e * CodeError) GetErrCode () int {return e.errCode} func (e * CodeError) GetErrMsg () string {return e.errMsg} func (e * CodeError) Error () string {return fmt.Sprintf ("ErrCode:%d ErrMsg:%s ", e.errCode, e.errMsg)} func New (errCode int, errMsg string) * CodeError {return & CodeError {errCode: errCode, errMsg: errMsg}} func NewErrCode (errCode int) * CodeError {return & CodeError {errCode: errCode, errMsg: MapErrMsg (errCode)} func NewErrMsg (errMsg string) * CodeError {return & CodeError {errCode: BAD_REUQEST_ERROR, errMsg: errMsg}}

Errmsg.go

Package xerrvar message map [int] stringfunc init () {message = make (map [int] string) message [OK] = "SUCCESS" message [bad _ REUQEST_ERROR] = "Server busy, please try again later" message [requests _ PARAM_ERROR] = "parameter error" message [user _ NOT_FOUND] = "user does not exist"} func MapErrMsg (errcode int) string {if msg, ok: = message [errcode] Ok {return msg} else {return "server is busy, please try again later"}}

Errcode.go

Package xerr// successfully returned const OK = 200amp / global error code / / the first three bits represent the business, and the last three bits represent the specific function const BAD_REUQEST_ERROR = 100001const REUQES_PARAM_ERROR = 100002 / user module const USER_NOT_FOUND = 200001

I put the three files in the lib/xerr directory

It is not enough to have an error code. We also need to define the result of uniformly returning http. The default generated by goctl is good, but it cannot meet my requirement of returning custom error code, so I have written a file that uniformly returns the result:

Httpresult:

Package xhttpimport ("fishtwo/lib/xerr"fmt"github.com/tal-tech/go-zero/core/logx"github.com/tal-tech/go-zero/rest/httpx"google.golang.org/grpc/status"net/http"github.com/pkg/errors") / / http method func HttpResult (r * http.Request,w http.ResponseWriter,resp interface {}) Err error) {if err = = nil {/ / successfully returned r Success = Success (resp) httpx.WriteJson (w, http.StatusOK, r)} else {/ / error returned errcode: = xerr.BAD_REUQEST_ERROR errmsg: = "Server busy Please try again later. "if eMagin ok: = err. (* xerr.CodeError)" Ok {/ / Custom CodeError errcode = e.GetErrCode () errmsg = e.GetErrMsg ()} else {originErr: = errors.Cause (err) / / err type if gstatus, ok: = status.FromError (originErr) Ok {/ / grpc err error errmsg = gstatus.Message ()}} logx.WithContext (r.Context ()) .error ("[GATEWAY-SRV-ERR]:% + v", err) httpx.WriteJson (w, http.StatusBadRequest, Error (errcode,errmsg))}} / / http parameter error returns func ParamErrorResult (r * http.Request,w http.ResponseWriter) Err error) {errMsg: = fmt.Sprintf ("% s,% s", xerr.MapErrMsg (xerr.REUQES_PARAM_ERROR), err.Error ()) httpx.WriteJson (w, http.StatusBadRequest, Error (xerr.REUQES_PARAM_ERROR,errMsg))}

Responsebean

Package xhttptype (NullJson struct {} ResponseSuccessBean struct {Code int `json: "code" `Msg string `json: "msg" `Data interface {} `json: "data" `}) func Success (data interface {}) * ResponseSuccessBean {return & ResponseSuccessBean {200, "OK", data}} type ResponseErrorBean struct {Code int `json: "code" `Msg string `json: "msg"`} func Error (errCode int,errMsg string) * ResponseErrorBean {return & ResponseErrorBean {errCode ErrMsg}}

Put it under lib/xhttp

Then the code generated by goctl under internal/handler/ is modified:

Of course, you will say, every time the generation is finished, you have to change it manually. How troublesome!

Here comes the template of Dangdangdang ~ ~ goctl, https://www.yuque.com/tal-tech/go-zero/mkpuit

Then modify ~ / .goctl/api/handler.tpl:

Package handlerimport ("net/http" {{.ImportPackages}}) func {{.HandlerName}} (ctx * svc.ServiceContext) http.HandlerFunc {return func (w http.ResponseWriter, r * http.Request) {if .HasRequest}} var req types. {{.RequestType}} if err: = httpx.Parse (r, & req) Err! = nil {xhttp.ParamErrorResult (rreco wrech er) return} {{end} l: = logic.New {{.LogicType}} (r.Context (), ctx) resp,err: = l.Login (req) xhttp.HttpResult (r recorder wrecorder er)}}

In the re-generation to see if it is beautiful,

Then talking about our gateway log, if users with good eyes have already seen the figure of log in the above httpresult.go:

Yes, this is fine, so that whenever there is an error, the log will be printed. Go-zero has already brought trace-id in, what? Trace-id doesn't know what it is? Um, in fact, it is to concatenate a request through this id. For example, if you user-api calls user- > srv or other srv, you need a unique label identification to concatenate their requests this time. This id is to do this, and there are a lot of link tracking, such as jaeger and zipkin.

RPC service

In model:rpc services, the official document recommends that model be placed under the services directory, one layer with each rpc service, but I feel that each model corresponds to a table, a table can only be controlled by one service, which service controls the table, which service has the right to control the model, and other services want to access through grpc, this is a personal idea, so I put the model controlled by each service in the internal.

Enum: in addition, I added the enum enumeration directory under the service, because other rpc services or api services will call this enumeration to compare. I put it outside the internal.

At this point, the study of "Enterprise Project Migration go-zero method tutorial" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report