0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Automating Sitemap Updates 🔎

Last updated at Posted at 2023-03-08

こんにちは。Enabling team の山本です。

今回は Search Console について書きます。

弊社では、Owned Media を運用しています。

メディアにとって、SEO は以前として重要な要素です。ChatGPT が盛り上がりを見せていますが。

新規出店に合わせて、チラシや店舗の情報を発信しているため、Sitemap の更新も欠かせません。

Sitemap の更新をタイムリーに行うため、Search Console の Sitemap 更新を自動化しましたので、その話を書きます。

TL;DR

  • サービス アカウントに権限を借用させると自動化できる。

構成

  • Cloud Functions
    • go1.20.1 linux/arm64

Webhook Trigger で起動する。
invoker は、CMS です。

準備

  • Google Cloud の Project で Google Search Console API を有効にする、
gcloud services enable searchconsole.googleapis.com --project=hoge-project-id
  • Google Service Account(GSA)を作成する。
  • GSA を Search Console に登録する。
  • GSA の Credentials Key を作成する。
  • Credentials Key を環境変数に設定する。

Sample Code

package main

import (
	"context"
	"fmt"
	"os"

	"google.golang.org/api/option"
	"google.golang.org/api/webmasters/v3"
)

func main() {
	ctx := context.Background()
	keyJson := os.Getenv("KEY_JSON")
	webmastersService, err := webmasters.NewService(ctx, option.WithCredentialsJSON([]byte(keyJson)))
	if err != nil {
		fmt.Println("Failed to create Client.")
	}
	siteUrl := os.Getenv("SITE_URL")
	fmt.Printf("siteUrl: %v\n", siteUrl)
	feedpath := os.Getenv("FEEDPATH")
	fmt.Printf("feedpath: %v\n", feedpath)
	err = webmastersService.Sitemaps.Submit(siteUrl, feedpath).Do()
	if err != nil {
		fmt.Println("Failed to submit.")
		fmt.Println(err)
	}
}
vscode ➜ /workspaces/hoge (main) $ go run main.go
siteUrl: sc-domain:example.co.jp
feedpath: https://www.example.co.jp/sitemap/sitemap.xml
vscode ➜ /workspaces/hoge (main) $

まとめ

Sitemap 更新の自動化について書きました。
最初は、OAuth で実装しましたが、Web 画面での認証が必要なため、サービス アカウントを使用した実装に変更しました。
こういう誰も拾わないような Toil を拾いながら、Programming をやっていこうと思います。
立場上、丸一日 Programming する時間もないため、今の僕にはちょうど良いレベルの課題です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?