Using package level variables is not always good or always bad. Depending on problem.
The only thing about this specific code example, is that you could possibly end up in a state where you are locking and unlocking in multiple places in code.
If you choose to go down this route; which is fine, consider extracting the tplPath
and mutex
into a type.
// create type and expose values through getters and setters
// to ensure the mutex logic is encapsulated.
type path struct {
mu sync.Mutex
val string
}
func (p *path) setPath(path string) {
p.mu.Lock()
defer p.mu.Unlock()
p.val = path
}
func (p *path) path() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.val
}
var tplPath *path
func init() {
// use package init to make sure path is always instantiated
tplPath = new(path)
}
func Prepare(c *gin.Context) {
tplPath.setPath("abc")
}