Name pickers are a common feature in Muslim parenting, family-tree and greeting-card apps. In this tutorial we build one in Go, using only the standard library:
- a CLI that lists Muslim names filtered by gender and by a search term,
- a disk cache so the data is downloaded at most once a day,
- a small JSON microservice (
GET /names?gender=female&lang=ur) that returns each name's meaning in the requested language, falling back to English, - unit tests with
httptest, so the tests never touch the network.
The data comes from the public sample JSON of the SunnahSource Islamic Names API.
1. Look at the data
curl -s https://sunnahsource.org/data/json/islamic-names.json The response is a small document with an items array. Each item has an Arabic name, an English name, a gender and meanings in 9 languages (en, ur, fr, de, tr, ms, ru, zh-CN, ja):
{ "title": "Islamic Names", "description": "Beautiful Muslim names for boys and girls with meanings", "is_free": false, "items": [ { "name_ar": "عَلِي", "name_en": "Ali", "gender": "male", "translations": { "en": "High, elevated, noble", "ur": "بلند، عالی، شریف", "de": "Hoch, edel" } } ] } (Translations trimmed for space.) The public file is a sample with a handful of names. The full dataset is part of the paid API, see the pricing page. The code below works the same way with both, because the shape is identical.
2. Project setup
mkdir names && cd names go mod init names Everything goes in one main.go. No third-party modules are needed.
3. Types that mirror the JSON
package main import ( "encoding/json" "flag" "fmt" "log" "net/http" "os" "sort" "strings" "time" ) const sourceURL = "https://sunnahsource.org/data/json/islamic-names.json" // Name mirrors one entry in the "items" array. type Name struct { NameAr string `json:"name_ar"` NameEn string `json:"name_en"` Gender string `json:"gender"` Translations map[string]string `json:"translations"` } // Dataset mirrors the top-level JSON document. type Dataset struct { Title string `json:"title"` Description string `json:"description"` IsFree bool `json:"is_free"` Items []Name `json:"items"` } translations is a flat map[string]string, so adding a new language on the server needs no code change.
4. Meaning with an English fallback, and filtering
// Meaning returns the meaning in lang, falling back to English. func (n Name) Meaning(lang string) string { if m, ok := n.Translations[lang]; ok && m != "" { return m } return n.Translations["en"] } // Filter returns names matching gender ("" = any) and a case-insensitive // query against the English name or the meaning in lang. func Filter(items []Name, gender, query, lang string) []Name { q := strings.ToLower(strings.TrimSpace(query)) var out []Name for _, n := range items { if gender != "" && !strings.EqualFold(n.Gender, gender) { continue } if q != "" && !strings.Contains(strings.ToLower(n.NameEn), q) && !strings.Contains(strings.ToLower(n.Meaning(lang)), q) { continue } out = append(out, n) } sort.Slice(out, func(i, j int) bool { return out[i].NameEn < out[j].NameEn }) return out } Searching the meaning as well as the name is what makes a name picker useful. A parent can type "noble" or "praised" and get matching names.
5. Download once, then cache on disk
// Load reads the cache file if it is fresh, otherwise downloads and caches it. func Load(url, cachePath string, maxAge time.Duration) (*Dataset, error) { if st, err := os.Stat(cachePath); err == nil && time.Since(st.ModTime()) < maxAge { if b, err := os.ReadFile(cachePath); err == nil { var d Dataset if json.Unmarshal(b, &d) == nil { return &d, nil } } } client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Get(url) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status %s", resp.Status) } var d Dataset if err := json.NewDecoder(resp.Body).Decode(&d); err != nil { return nil, err } if b, err := json.Marshal(d); err == nil { _ = os.WriteFile(cachePath, b, 0o644) } return &d, nil } Two details matter here. Always set a client Timeout, because Go's default client waits forever. And if the cache file is corrupt, the code just falls through and downloads a fresh copy.
6. The HTTP microservice
type apiName struct { Arabic string `json:"arabic"` English string `json:"english"` Gender string `json:"gender"` Meaning string `json:"meaning"` } // Handler serves GET /names?gender=female&lang=ur&q=noble func Handler(d *Dataset) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { lang := r.URL.Query().Get("lang") if lang == "" { lang = "en" } res := []apiName{} for _, n := range Filter(d.Items, r.URL.Query().Get("gender"), r.URL.Query().Get("q"), lang) { res = append(res, apiName{n.NameAr, n.NameEn, n.Gender, n.Meaning(lang)}) } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "public, max-age=3600") _ = json.NewEncoder(w).Encode(map[string]any{"count": len(res), "lang": lang, "names": res}) } } Starting res as []apiName{} rather than nil means an empty result is encoded as [], not null. Front-end code will thank you.
7. Wire up the CLI
func main() { gender := flag.String("gender", "", "male or female (empty = both)") lang := flag.String("lang", "en", "en, ur, fr, de, tr, ms, ru, zh-CN, ja") query := flag.String("q", "", "search the name or its meaning") serve := flag.String("serve", "", "listen address, e.g. :8080 (starts the HTTP API)") flag.Parse() d, err := Load(sourceURL, "islamic-names.cache.json", 24*time.Hour) if err != nil { log.Fatal(err) } if *serve != "" { http.HandleFunc("/names", Handler(d)) log.Printf("listening on %s", *serve) log.Fatal(http.ListenAndServe(*serve, nil)) } for _, n := range Filter(d.Items, *gender, *query, *lang) { fmt.Printf("%-10s %-8s %-7s %s\n", n.NameEn, n.NameAr, n.Gender, n.Meaning(*lang)) } } 8. Run it
$ go run . -gender female Aisha عَائِشَة female Living, prosperous — wife of Prophet (SAW) Fatima فَاطِمَة female One who abstains — daughter of Prophet (SAW) $ go run . -lang ur -q yusuf Yusuf يُوسُف male اللہ بڑھاتا ہے — حضرت یوسف علیہ السلام And as a service:
$ go run . -serve :8080 $ curl 'localhost:8080/names?gender=male&lang=de' {"count":3,"lang":"de","names":[{"arabic":"عَلِي","english":"Ali","gender":"male","meaning":"Hoch, edel"},{"arabic":"مُحَمَّد","english":"Muhammad","gender":"male","meaning":"Gepriesener — Name des letzten Propheten"},{"arabic":"يُوسُف","english":"Yusuf","gender":"male","meaning":"Allah mehrt"}]} (Arabic and Urdu are right-to-left. In a terminal the column alignment can look a little off. In a browser, wrap them in an element with dir="rtl".)
9. Tests without the network
httptest.NewServer gives the loader a fake upstream, so the tests check the cache logic and never call the real API:
package main import ( "encoding/json" "net/http" "net/http/httptest" "path/filepath" "testing" "time" ) var sample = []Name{ {NameAr: "عَلِي", NameEn: "Ali", Gender: "male", Translations: map[string]string{"en": "High, elevated, noble", "ur": "بلند، عالی، شریف"}}, {NameAr: "فَاطِمَة", NameEn: "Fatima", Gender: "female", Translations: map[string]string{"en": "One who abstains"}}, } func TestFilterQueryMeaning(t *testing.T) { if got := Filter(sample, "", "noble", "en"); len(got) != 1 || got[0].NameEn != "Ali" { t.Fatalf("got %+v", got) } } func TestMeaningFallback(t *testing.T) { if m := sample[1].Meaning("ur"); m != "One who abstains" { t.Fatalf("fallback failed: %q", m) } } func TestLoadAndCache(t *testing.T) { calls := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ _ = json.NewEncoder(w).Encode(Dataset{Title: "Islamic Names", Items: sample}) })) defer srv.Close() cache := filepath.Join(t.TempDir(), "c.json") for i := 0; i < 2; i++ { if d, err := Load(srv.URL, cache, time.Hour); err != nil || len(d.Items) != 2 { t.Fatalf("load %d: %v", i, err) } } if calls != 1 { t.Fatalf("expected 1 network call, got %d", calls) } } func TestHandler(t *testing.T) { rec := httptest.NewRecorder() Handler(&Dataset{Items: sample})(rec, httptest.NewRequest("GET", "/names?gender=male&lang=ur", nil)) var body struct { Count int `json:"count"` Names []apiName `json:"names"` } if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Count != 1 || body.Names[0].Meaning != "بلند، عالی، شریف" { t.Fatalf("bad body %s", rec.Body.String()) } } $ go test ./... ok names 0.006s 10. Going further
- Add background for well-known names. Many Muslim names are names of prophets (such as Yusuf) or companions (such as Ali). You can show a short biography next to them with the Prophets Stories (Ambiya) API and the Sahaba API.
- Names of Allah are a different list. If you also want the 99 Names (Asma ul Husna), use the Asma ul Husna API instead of mixing them into a baby-name list.
- Deploy. The binary is a single static file.
CGO_ENABLED=0 go buildand copy it to any small VPS or container.
Source and links
- SunnahSource Islamic Names API: https://sunnahsource.org/apis/islamic-names/
- All SunnahSource Islamic APIs (Quran, Hadith, Duas, Prayer Times and more): https://sunnahsource.org/
- GitHub: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api
If you build something with it, share it in the comments.