font: initialize default font once

This commit is contained in:
Jaroslavs Samcuks 2021-06-08 19:20:31 +02:00
parent c1468e8ae4
commit 29d53b2e35

27
font.go
View file

@ -7,23 +7,22 @@ import (
"github.com/wcharczuk/go-chart/v2/roboto"
)
var (
_defaultFontLock sync.Mutex
_defaultFont *truetype.Font
)
var _defaultFont defaultFont
// GetDefaultFont returns the default font (Roboto-Medium).
func GetDefaultFont() (*truetype.Font, error) {
if _defaultFont == nil {
_defaultFontLock.Lock()
defer _defaultFontLock.Unlock()
if _defaultFont == nil {
font, err := truetype.Parse(roboto.Roboto)
if err != nil {
return nil, err
return _defaultFont.Font()
}
_defaultFont = font
type defaultFont struct {
font *truetype.Font
err error
once sync.Once
}
}
return _defaultFont, nil
func (df *defaultFont) Font() (*truetype.Font, error) {
df.once.Do(func() {
df.font, df.err = truetype.Parse(roboto.Roboto)
})
return df.font, df.err
}