I want to know if gin framework provides listener service? E.g,during the startup process of gin, we can initialize mysql and register it to *gin.Context by start listener.
Comment From: mohsalsaleem
As per my understanding, the gin.Context is set per request and not during startup, in case that is something you are not aware of. Do you have some other use-case as well where you intend to use the listener?
Comment From: zhangtao-sw
Thank you for your reply. use-case: I want to use a custom log object to log in this route handle function,i should import 'global' and use global.GVA_LOG object to log message. import "global" func (b BaseApi) Login(c gin.Context) { global.GVA_LOG.Error("login fail!", zap.Error(err)) }
but if i can register the GVA_LOG obj to gin.Context, the i can use the GVA_LOG more conveniently func (b BaseApi) Login(c *gin.Context) { c.GVA_LOG.Error("login fail!", zap.Error(err)) }
The GVA_LOG object(struct) can register to server by start listener , and i can free GVA_LOG obj by end listener.
In python web frameworks there are usually listeners to handle such requirements, so I wonder if there is a listener in the gin framework?
Comment From: mohsalsaleem
Is the GVA_LOG
route specific? If that is the case, you can set that in gin.Context using a middleware, get that and use that inside your route handler function.
If it is global, it makes sense to import and use it in everywhere you need, as it will reduce the per-request memory footprint (if GVA_LOG
is to be set for every request in gin.Context)
Comment From: zhangtao-sw
I think you are right. Considering the memory, GVA_LOG should not be registered in the service. I think it's a difference in golang and python coding. I am a beginner in golang. Can I ask if it is necessary to use async to handle io time-consuming work in the gin framework? In the python web framework, using async to handle io task(mysql,redis..) is a necessary to improve service concurrency.
Or can you tell me the best way to do mysql work in gin framework? I want to implement a web service with high concurrency capability. "github.com/jmoiron/sqlx" ->is this library enough for gin web framework?
Comment From: mohsalsaleem
Well, gin should provide you with very good concurrency performance by default. Regarding handling of time-consuming work, if it takes a long time (> 1s-2s), I'd personally off load it to a an async system that handles it in the background. But again, it is a matter of architectural decision of how you want to design your APIs.
Unless your DB operations are resource heavy, and time consuming, or requires handling multiple resource updates simultaneously, you really do not need to do the operations asynchronously.
Comment From: zhangtao-sw
Thanks for your patient reply!