I am writing a post code location lookup package, it loads in all uk postcodes from a csv, I would like to only load the data once I would like to know what is the best pattern to achieve this with Go.
type Location struct {
Latitude float64
Longitude float64
}
var postCodeCache = make(map[string]Location)
These are my data types, currently I have a function called LoadData and LookupPostCode(). Ideally I would want to import my package and it would automatically load the data if it was not already loaded.
You've got two options:
The simplest is load the data in main before any other processing starts. If probability that you will read the data is very high and there is no other reason to avoid doing it immediately, why not?
Load the data with sync.Once. Something like:
var dataLoaded sync.Once
var data DataType = nil
func LookupPostCode(some_args) {
once.Do(func() {
data = LoadData(some_subset_of_some_args)
})
// and here I know, that data are loaded
}
You can use init() function in your package to do this.
Or, if it does not change frequently, you can convert your CSV into a Go Map definition in a separate .go file and it will be 'loaded' at the compile time.