diff --git a/wrapper.go b/wrapper.go index cdd601c..c2470d7 100644 --- a/wrapper.go +++ b/wrapper.go @@ -15,6 +15,12 @@ import ( "runtime" "strconv" "strings" + "sync" +) + +var ( + storefrontCache map[int]string + storefrontCacheOnce sync.Once ) func parseStorefrontID(id string) string { @@ -22,26 +28,30 @@ func parseStorefrontID(id string) string { if err != nil { panic(err) } - type StorefrontMapping struct { - Name string `json:"name"` - Code string `json:"code"` - StorefrontId int `json:"storefrontId"` - } - var mapping []StorefrontMapping - file, err := os.ReadFile("data/storefront_ids.json") - if err != nil { - panic(err) - } - err = json.Unmarshal(file, &mapping) - if err != nil { - panic(err) - } - for _, element := range mapping { - if element.StorefrontId == sfID { - return element.Code + + storefrontCacheOnce.Do(func() { + type StorefrontMapping struct { + Name string `json:"name"` + Code string `json:"code"` + StorefrontId int `json:"storefrontId"` } - } - return "" + var mapping []StorefrontMapping + file, err := os.ReadFile("data/storefront_ids.json") + if err != nil { + panic(err) + } + err = json.Unmarshal(file, &mapping) + if err != nil { + panic(err) + } + + storefrontCache = make(map[int]string) + for _, element := range mapping { + storefrontCache[element.StorefrontId] = element.Code + } + }) + + return storefrontCache[sfID] } func PrepareWrapper(mirror bool) { diff --git a/wrapper_test.go b/wrapper_test.go new file mode 100644 index 0000000..1ed21fd --- /dev/null +++ b/wrapper_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "os" + "testing" +) + +func setupStorefrontFile() (func(), error) { + const filename = "data/storefront_ids.json" + originalContent, err := os.ReadFile(filename) + originalExists := err == nil + + content := `[{"name":"United States","code":"us","storefrontId":143441},{"name":"China","code":"cn","storefrontId":143465}]` + _ = os.MkdirAll("data", 0755) + _ = os.WriteFile(filename, []byte(content), 0644) + + teardown := func() { + os.Remove(filename) + if originalExists { + os.WriteFile(filename, originalContent, 0644) + } + } + return teardown, nil +} + +func TestParseStorefrontID(t *testing.T) { + teardown, _ := setupStorefrontFile() + defer teardown() + + // Verify known ID + code := parseStorefrontID("143441-1,29") + if code != "us" { + t.Errorf("Expected 'us', got '%s'", code) + } + + // Verify another known ID + code = parseStorefrontID("143465-something") + if code != "cn" { + t.Errorf("Expected 'cn', got '%s'", code) + } +} + +func BenchmarkParseStorefrontID(b *testing.B) { + teardown, _ := setupStorefrontFile() + defer teardown() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = parseStorefrontID("143441-1,29") + } +}