---
title: "ルーティング、ローカライズ、マルチサイトを実装する"
slug: "implement-routing-localization-and-multi-sites"
abstract: "サイト解像度、ロケール解像度、リダイレクト処理をSitecoreAIコンテンツをレンダリングするフロントエンドアプリに追加する方法。"
---
# ルーティング、ローカライズ、マルチサイトを実装する

この手順は、アプリ [内のRender SitecoreAIコンテンツ](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html "Render SitecoreAI content in your app")の基礎を基にしており、環境変数から単一のサイト名と言語をハードコードします。この手順では、これらのハードコードされた値をリクエスト時の解決に置き換え、アプリが複数のサイトや言語に対応し、コンテンツ管理リダイレクトを尊重できるようにします。

このウォークスルーでは、Astro 7およびGoのフロントエンドアプリケーション向けのコード例を提供し、以下の方法を説明します:

:::攻略

1.  [サイトリストの取得とキャッシュ](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#fetch-and-cache-your-site-list)
2.  [リクエストホスト名からサイトを解決する](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#resolve-the-site-from-the-request-hostname)
3.  [リクエストパスからロケールを解決する](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#resolve-the-locale-from-the-request-path)
4.  [リダイレクトの取得と評価](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#fetch-and-evaluate-redirects)
5.  [サイト辞書をクエリする](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#query-the-site-dictionary)
6.  [ルーティングへのワイヤー解像度](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#wire-resolution-into-your-routing)
7.  [アプリをテストしてください](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/implement-routing-localization-and-multi-sites.html#test-your-app):::

> !注**始める前に**
> 
> -   [アプリ内のSitecoreAIのレンダリングコンテンツ](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html "Render SitecoreAI content in your app")と、[ビジュアル編集を有効にする](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/visual-editing/enable-visual-editing.html)手順を完了してください。この手順は、前の手順で作成したアプリを直接基にしています。
> -   [マルチサイト解像度](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/multisite-resolution.html "Multi-site resolution")、[ロケール解像度](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/locale-resolution.html "Locale resolution")、および概念[のリダイレクト](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/redirects.html "Redirects")を確認します。
> -   この手順では、SitecoreAI 環境が少なくとも 1 つの追加サイトまたは言語が設定されていることを前提としています。サイトと言語が1つだけであっても、引き続きフォローできます。サイトおよびロケールの解決は常に設定した1つの値に解決されます。

## サイトリストの取得とキャッシュ

環境のサイトリストを取得し、メモリにキャッシュする関数を追加し、すべてのリクエストでクエリしないようにしましょう。

:::::タブ:tab{title="Astro"}

1.  src/services/sitecoreClient.jsに追加する:
    
    // src/services/sitecoreClient.js
    
    let siteListCache = null;
    
    export async function fetchSiteList() {
     if (siteListCache) {
     return siteListCache;
     }
    
     const env = import.meta.env;
     const endpoint = env.SITECORE\_EDGE\_PLATFORM\_URL;
     const contextId = env.SITECORE\_EDGE\_CONTEXT\_ID;
    
     const query = \`
     query SiteInfoCollectionQuery {
     site {
     siteInfoCollection { name hostname language }
     }
     }
     \`;
    
     const response = await fetch(endpoint, {
     method: "POST",
     headers: {
     "Content-Type": "application/json",
     "x-sitecore-contextid": contextId,
     },
     body: JSON.stringify({ query }),
     });
    
     const result = await response.json();
    
     if (result.errors) {
     throw new Error(JSON.stringify(result.errors));
     }
    
     siteListCache = result?.data?.site?.siteInfoCollection || ;
     return siteListCache;
    }
    

::::::tab{title="Go"}

1.  main.goに追加する:
    
    // main.go
    
    type siteInfo struct {
     Name string \`json:"name"\`
     Hostname string \`json:"hostname"\`
     Language string \`json:"language"\`
    }
    
    var siteListCache siteInfo
    
    func fetchSiteList() (siteInfo, error) {
     if siteListCache != nil {
     return siteListCache, nil
     }
    
     endpoint := os.Getenv("SITECORE\_EDGE\_PLATFORM\_URL")
     contextID := os.Getenv("SITECORE\_EDGE\_CONTEXT\_ID")
    
     query := \`
     query SiteInfoCollectionQuery {
     site {
     siteInfoCollection { name hostname language }
     }
     }
     \`
    
     body, \_ := json.Marshal(mapstringany{"query": query})
     req, \_ := http.NewRequest("POST", endpoint, bytes.NewReader(body))
     req.Header.Set("Content-Type", "application/json")
     req.Header.Set("x-sitecore-contextid", contextID)
    
     resp, err := http.DefaultClient.Do(req)
     if err != nil {
     return nil, err
     }
     defer resp.Body.Close()
    
     var result struct {
     Data struct {
     Site struct {
     SiteInfoCollection siteInfo \`json:"siteInfoCollection"\`
     } \`json:"site"\`
     } \`json:"data"\`
     Errors any \`json:"errors"\`
     }
     if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
     return nil, err
     }
     if result.Errors != nil {
     return nil, fmt.Errorf("%v", result.Errors)
     }
    
     siteListCache = result.Data.Site.SiteInfoCollection
     return siteListCache, nil
    }
    

:::::::

## リクエストホスト名からサイトを解決する

リクエストのホスト名をキャッシュされたサイトリストと照合する関数を追加し、設定済みのデフォルトサイトにフォールバックします。

:::::タブ:tab{title="Astro"}

1.  src/services/sitecoreClient.jsに追加する:
    
    // src/services/sitecoreClient.js
    
    export function resolveSite(hostname, sites, defaultSiteName) {
     const match = sites.find((site) =>
     site.hostname
     .split(/\\||,|;/)
     .map((h) => h.trim().toLowerCase())
     .some((h) => hostnameMatches(hostname.toLowerCase(), h))
     );
    
     return match || sites.find((site) => site.name === defaultSiteName);
    }
    
    function hostnameMatches(hostname, pattern) {
     if (!pattern) return false;
     const regex = new RegExp(
     "^" + pattern.replace(/\\./g, "\\\\.").replace(/\\\*/g, ".\*") + "$",
     "i"
     );
     return regex.test(hostname);
    }
    
2.  ハードコードされた環境変数ではなく、リクエストからサイトを解決するために更新src/pages/...slug.astro :
    
    \---
    // src/pages/...slug.astro
    import { fetchLayoutData, fetchSiteList, resolveSite } from '../services/sitecoreClient.js';
    
    export const prerender = false;
    
    const sites = await fetchSiteList();
    const site = resolveSite(
     Astro.url.hostname,
     sites,
     import.meta.env.SITECORE\_SITE\_NAME
    );
    ---
    

::::::tab{title="Go"}

1.  main.goに追加する:
    
    // main.go
    import "regexp"
    
    func resolveSite(hostname string, sites siteInfo, defaultSiteName string) siteInfo {
     hostname = strings.ToLower(hostname)
    
     for \_, site := range sites {
     for \_, pattern := range strings.Split(site.Hostname, "|") {
     pattern = strings.ToLower(strings.TrimSpace(pattern))
     if pattern == "" {
     continue
     }
     escaped := strings.ReplaceAll(regexp.QuoteMeta(pattern), \`\\\*\`, ".\*")
     if matched, \_ := regexp.MatchString("^"+escaped+"$", hostname); matched {
     return site
     }
     }
     }
    
     for \_, site := range sites {
     if site.Name == defaultSiteName {
     return site
     }
     }
     return siteInfo{}
    }
    
2.  ルートハンドラーを更新し、ハードコードされた環境変数ではなく、リクエストのHostヘッダーからサイトを解決するよう:
    
    // main.go
    sites, err := fetchSiteList()
    if err != nil {
     log.Fatal(err)
    }
    defaultSiteName := os.Getenv("SITECORE\_SITE\_NAME")
    
    http.HandleFunc("/", func(w http.ResponseWriter, r \*http.Request) {
     site := resolveSite(r.Host, sites, defaultSiteName)
     // ... use site.Name in place of the hard-coded site variable
    })
    

:::::::

## リクエストパスからロケールを解決する

次に、リクエストパスからロケールセグメント(例: /fr-fr/products)を抽出し、ロケールセグメントが存在しない場合は解決済みサイトのデフォルト言語にフォールバックします。

:::::タブ:tab{title="Astro"}

1.  src/services/sitecoreClient.jsに追加する:
    
    // src/services/sitecoreClient.js
    
    export function resolveLocale(slugSegments, configuredLocales, defaultLocale) {
     const first, ...rest = slugSegments;
     const match = configuredLocales.find(
     (locale) => locale.toLowerCase() === (first || "").toLowerCase()
     );
    
     if (match) {
     return { locale: match, remainingSegments: rest };
     }
     return { locale: defaultLocale, remainingSegments: slugSegments };
    }
    
2.  ロケールを解決し、ルートパスからロケールを除去するにはsrc/pages/...slug.astroを更新してください:
    
    \---
    // src/pages/...slug.astro
    const configuredLocales = (import.meta.env.SITECORE\_SITE\_LOCALES || "en").split(",");
    const slugSegments = Astro.params.slug ? Astro.params.slug.split('/') : ;
    const { locale, remainingSegments } = resolveLocale(
     slugSegments,
     configuredLocales,
     site.language
    );
    let routePath = remainingSegments.length ? \`/${remainingSegments.join('/')}\` : '/';
    ---
    

::::::tab{title="Go"}

1.  main.goに追加する:
    
    // main.go
    
    func resolveLocale(segments string, configuredLocales string, defaultLocale string) (string, string) {
     if len(segments) == 0 {
     return defaultLocale, segments
     }
     for \_, locale := range configuredLocales {
     if strings.EqualFold(locale, segments0) {
     return locale, segments1:
     }
     }
     return defaultLocale, segments
    }
    
2.  ルートハンドラーを更新してロケールを解決し、ルートパスから除外します:
    
    // main.go
    configuredLocales := strings.Split(os.Getenv("SITECORE\_SITE\_LOCALES"), ",")
    
    segments := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
    locale, remaining := resolveLocale(segments, configuredLocales, site.Language)
    routePath := "/" + strings.Join(remaining, "/")
    

:::::::

## リダイレクトの取得と評価

レイアウトデータを取得する前に、サイトのリダイレクトルールを取得し、現在のリクエストと照合する関数を追加します。

:::::タブ:tab{title="Astro"}

1.  src/services/sitecoreClient.jsに追加する:
    
    // src/services/sitecoreClient.js
    
    const redirectsCache = new Map();
    
    export async function fetchRedirects(site) {
     if (redirectsCache.has(site)) {
     return redirectsCache.get(site);
     }
    
     const env = import.meta.env;
     const query = \`
     query RedirectsQuery($siteName: String!) {
     site {
     siteInfo(site: $siteName) {
     redirects {
     pattern target redirectType isQueryStringPreserved isLanguagePreserved locale
     }
     }
     }
     }
     \`;
    
     const response = await fetch(env.SITECORE\_EDGE\_PLATFORM\_URL, {
     method: "POST",
     headers: {
     "Content-Type": "application/json",
     "x-sitecore-contextid": env.SITECORE\_EDGE\_CONTEXT\_ID,
     },
     body: JSON.stringify({ query, variables: { siteName: site } }),
     });
    
     const result = await response.json();
     const redirects = result?.data?.site?.siteInfo?.redirects || ;
     redirectsCache.set(site, redirects);
     return redirects;
    }
    
    export function matchRedirect(redirects, routePath, locale) {
     return redirects.find((redirect) => {
     if (redirect.locale && redirect.locale !== locale) {
     return false;
     }
     if (isRegex(redirect.pattern)) {
     return new RegExp(redirect.pattern, "i").test(routePath);
     }
     return redirect.pattern.replace(/\\/$/, "") === routePath.replace(/\\/$/, "");
     });
    }
    
    function isRegex(pattern) {
     // Simple heuristic: treat patterns with regex metacharacters as regular expressions.
     return /()^$|\\/.test(pattern);
    }
    
2.  レイアウトデータを取得する前に、src/pages/...slug.astroでマッチングされたリダイレクトを適用します。 SERVER\_TRANSFERをHTTPリダイレクトではなく内部書き換えとして扱い、表示されるURLが変わらないようにしてください:
    
    \---
    const redirects = await fetchRedirects(site.name);
    const matched = matchRedirect(redirects, routePath, locale);
    
    if (matched) {
     if (matched.redirectType === "SERVER\_TRANSFER") {
     // Keep the visible URL the same; fetch layout data for the target instead.
     routePath = matched.target;
     } else {
     const status = matched.redirectType === "REDIRECT\_301" ? 301 : 302;
     return Astro.redirect(matched.target, status);
     }
    }
    ---
    

::::::tab{title="Go"}

1.  main.goに追加する:
    
    // main.go
    
    type redirectRule struct {
     Pattern string \`json:"pattern"\`
     Target string \`json:"target"\`
     RedirectType string \`json:"redirectType"\`
     IsQueryStringPreserved bool \`json:"isQueryStringPreserved"\`
     IsLanguagePreserved bool \`json:"isLanguagePreserved"\`
     Locale \*string \`json:"locale"\`
    }
    
    var redirectsCache = mapstringredirectRule{}
    
    func fetchRedirects(site string) (redirectRule, error) {
     if cached, ok := redirectsCachesite; ok {
     return cached, nil
     }
    
     query := \`
     query RedirectsQuery($siteName: String!) {
     site {
     siteInfo(site: $siteName) {
     redirects {
     pattern target redirectType isQueryStringPreserved isLanguagePreserved locale
     }
     }
     }
     }
     \`
     body, \_ := json.Marshal(mapstringany{
     "query": query,
     "variables": mapstringany{"siteName": site},
     })
     req, \_ := http.NewRequest("POST", os.Getenv("SITECORE\_EDGE\_PLATFORM\_URL"), bytes.NewReader(body))
     req.Header.Set("Content-Type", "application/json")
     req.Header.Set("x-sitecore-contextid", os.Getenv("SITECORE\_EDGE\_CONTEXT\_ID"))
    
     resp, err := http.DefaultClient.Do(req)
     if err != nil {
     return nil, err
     }
     defer resp.Body.Close()
    
     var result struct {
     Data struct {
     Site struct {
     SiteInfo struct {
     Redirects redirectRule \`json:"redirects"\`
     } \`json:"siteInfo"\`
     } \`json:"site"\`
     } \`json:"data"\`
     }
     if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
     return nil, err
     }
    
     redirectsCachesite = result.Data.Site.SiteInfo.Redirects
     return redirectsCachesite, nil
    }
    
    func matchRedirect(redirects redirectRule, routePath, locale string) \*redirectRule {
     for \_, r := range redirects {
     if r.Locale != nil && \*r.Locale != locale {
     continue
     }
     if isRegex(r.Pattern) {
     if matched, \_ := regexp.MatchString(r.Pattern, routePath); matched {
     return &r
     }
     continue
     }
     if strings.TrimRight(r.Pattern, "/") == strings.TrimRight(routePath, "/") {
     return &r
     }
     }
     return nil
    }
    
    func isRegex(pattern string) bool {
     return strings.ContainsAny(pattern, "()^$|")
    }
    
2.  レイアウトデータを取得する前に、ルートハンドラーでマッチドリダイレクトを適用してください。 SERVER\_TRANSFERをHTTPリダイレクトではなく内部書き換えとして扱い、表示されるURLが変わらないようにしてください。
    
    // main.go
    redirects, err := fetchRedirects(site.Name)
    if err == nil {
     if matched := matchRedirect(redirects, routePath, locale); matched != nil {
     if matched.RedirectType == "SERVER\_TRANSFER" {
     // Keep the visible URL the same; fetch layout data for the target instead.
     routePath = matched.Target
     } else {
     status := http.StatusFound
     if matched.RedirectType == "REDIRECT\_301" {
     status = http.StatusMovedPermanently
     }
     http.Redirect(w, r, matched.Target, status)
     return
     }
     }
    }
    

:::::::

> !noteこれらのマッチング機能は、手順解のために簡略化されています。正則表現ターゲットにおけるキャプチャグループ置換、$siteLangトークン、クエリ文字列/ロケールの保存を含む完全な評価ロジックについてはリ[ダイレクト](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/redirects.html "Redirects")を参照してください。

## サイト辞書をクエリする

解決済みのサイトとロケールの [サイト辞書](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/locale-resolution.html#site-dictionary "Locale resolution") を取得し、コンポーネントがページコンテンツと並行して翻訳されたUI文字列を検索できるようにします。

:::::タブ:tab{title="Astro"}

1.  src/services/sitecoreClient.jsに追加する:
    
    // src/services/sitecoreClient.js
    const dictionaryCache = new Map();
    
    export async function fetchDictionary(site, language) {
     const cacheKey = \`${site}:${language}\`;
     if (dictionaryCache.has(cacheKey)) {
     return dictionaryCache.get(cacheKey);
     }
    
     const env = import.meta.env;
     const dictionary = {};
     let after = null;
     let hasNext = true;
    
     while (hasNext) {
     const response = await fetch(env.SITECORE\_EDGE\_PLATFORM\_URL, {
     method: "POST",
     headers: {
     "Content-Type": "application/json",
     "x-sitecore-contextid": env.SITECORE\_EDGE\_CONTEXT\_ID,
     },
     body: JSON.stringify({
     query: \`query($siteName: String!, $language: String!, $after: String) {
     site {
     siteInfo(site: $siteName) {
     dictionary(language: $language, first: 100, after: $after) {
     results { key value }
     pageInfo { endCursor hasNext }
     }
     }
     }
     }\`,
     variables: { siteName: site, language, after },
     }),
     });
    
     const { data } = await response.json();
     const page = data.site.siteInfo.dictionary;
     for (const entry of page.results) {
     dictionaryentry.key = entry.value;
     }
     hasNext = page.pageInfo.hasNext;
     after = page.pageInfo.endCursor;
     }
    
     dictionaryCache.set(cacheKey, dictionary);
     return dictionary;
    }
    
2.  レイアウトデータと一緒にsrc/pages/...slug.astroで取得します:
    
    \---
    const dictionary = await fetchDictionary(site.name, locale);
    ---
    
    [前のウォークスルー](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html "Render SitecoreAI content in your app")で作成されたサンプルコンポーネントは辞書キーを読み取らないので、このウォークスルーではそれ以上dictionary接続しません。自分のアプリではレイアウトやコンポーネントレンダリングに渡し、コンポーネントがキーごとに翻訳された文字列を検索できるようにします。
    

::::::tab{title="Go"}

1.  main.goに追加する:
    
    // main.go
    var dictionaryCache = mapstringmapstringstring{}
    
    func fetchDictionary(site, language string) (mapstringstring, error) {
     cacheKey := site + ":" + language
     if cached, ok := dictionaryCachecacheKey; ok {
     return cached, nil
     }
    
     dictionary := mapstringstring{}
     var after \*string
    
     for {
     body, \_ := json.Marshal(mapstringinterface{}{
     "query": \`query($siteName: String!, $language: String!, $after: String) {
     site {
     siteInfo(site: $siteName) {
     dictionary(language: $language, first: 100, after: $after) {
     results { key value }
     pageInfo { endCursor hasNext }
     }
     }
     }
     }\`,
     "variables": mapstringinterface{}{"siteName": site, "language": language, "after": after},
     })
     req, \_ := http.NewRequest("POST", os.Getenv("SITECORE\_EDGE\_PLATFORM\_URL"), bytes.NewReader(body))
     req.Header.Set("Content-Type", "application/json")
     req.Header.Set("x-sitecore-contextid", os.Getenv("SITECORE\_EDGE\_CONTEXT\_ID"))
    
     resp, err := http.DefaultClient.Do(req)
     if err != nil {
     return nil, err
     }
     defer resp.Body.Close()
    
     var result struct {
     Data struct {
     Site struct {
     SiteInfo struct {
     Dictionary struct {
     Results struct {
     Key string \`json:"key"\`
     Value string \`json:"value"\`
     } \`json:"results"\`
     PageInfo struct {
     EndCursor string \`json:"endCursor"\`
     HasNext bool \`json:"hasNext"\`
     } \`json:"pageInfo"\`
     } \`json:"dictionary"\`
     } \`json:"siteInfo"\`
     } \`json:"site"\`
     } \`json:"data"\`
     }
     if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
     return nil, err
     }
    
     page := result.Data.Site.SiteInfo.Dictionary
     for \_, entry := range page.Results {
     dictionaryentry.Key = entry.Value
     }
     if !page.PageInfo.HasNext {
     break
     }
     after = &page.PageInfo.EndCursor
     }
    
     dictionaryCachecacheKey = dictionary
     return dictionary, nil
    }
    
2.  ルートハンドラーで呼び出し、レイアウトデータも取得します。 [前のウォークスルー](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html "Render SitecoreAI content in your app") で構築されたサンプルコンポーネントは辞書キーを読み取らないため、このウォークスルーでは結果をさらに配線しません。自分のアプリでは、コンポーネントレンダに渡して、コンポーネントがキーごとに翻訳された文字列を検索できるようにします。
    

:::::::

> !noteもしフレームワークが静的サイト生成をサポートしている場合、リクエストが入ってくるたびに1つのパスを解決するのではなく、[routesクエリ](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/locale-resolution.html#enumerating-pages-for-static-generation "Locale resolution")を使ってサイトと言語のすべてのページを最初に列挙できます。

## ルーティングへのワイヤー解像度

サイト、ロケール、リダイレクトの解決が完了したところで、fetchLayoutData呼び出しを更新し、前の手順でハードコードされた環境変数の代わりに解決済みのサイト名とロケールを使用するようにしてください。

:::::タブ:tab{title="Astro"}

\---
// src/pages/...slug.astro
let layoutData;
try {
 layoutData = await fetchLayoutData(site.name, locale, routePath);
} catch (error) {
 return Astro.redirect('/404');
}

if (!layoutData) {
 return Astro.redirect('/404'); // Sitecore returned null; the route doesn't exist.
}
---

::::::tab{title="Go"}

// main.go
data, err := fetchLayoutData(site.Name, locale, routePath)
if err != nil {
 http.Error(w, err.Error(), http.StatusInternalServerError)
 return
}
if data == nil {
 http.Redirect(w, r, "/404", http.StatusFound) // Sitecore returned null; the route doesn't exist.
 return
}

:::::::

## アプリをテストする

1.  この手順 resolveLocale では、URLのロケールセグメントをアプリの設定済みロケールリストと照らし合わせて検証するため、SitecoreAIサイトの言語に合わせて、 .env ファイルのリスト(例: SITECORE\_SITE\_LOCALES=en,fr-fr)を一度限りのセットアップステップとして新しいロケールを追加してください。
2.  開発サーバーを再起動してください。
3.  /fr-frなどのロケールセグメントを含むルートパスを要求し、返されるレイアウトデータがその言語を反映していることを確認します。
4.  環境に複数のサイトが構成されている場合は、デフォルトのサイトでないホスト名(例:ローカルホストファイルを編集して)でテストし、正しいサイトのコンテンツが返されることを確認します。
5.  コンテンツ作成者に、サイトのリダイレクトマップにテストリダイレクトルールを追加するよう依頼してください(または [コンテンツエディター](https://doc.sitecore.com/sai/en/users/sitecoreai/manage-content/content-editor/redirect-urls.html)を使って自分で追加してください)。その後、リダイレクトのソースパスを要求し、アプリのリダイレクトが期待通りに行われることを確認します。
6.  解決済みの辞書オブジェクトを一時的にログに記録することでサイト辞書が入力されているか確認し、既知のキーが期待される翻訳値を返しているか確認します。

## 次のステップ { .notintoc }

問題が発生した場合は、「 [トラブルシューティング](https://doc.sitecore.com/sai/ja/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/routing-localization-and-multi-sites/troubleshoot-routing-localization-and-multi-sites.html "Troubleshooting")」を参照してください。