PIYO - Tech & Life -

Go lang + EchoでGoogle Analytics APIの結果をHugoから使えるように

Go" echo

またもやHugo用にGoのサーバーにAPIを追加しました。HugoでGoogle Analyticsで取っているPV順に並べた結果を使ってコンテンツを作るためです。

似たようなことをこの辺↓↓で書いてます。

https://blog.piyo.tech/posts/2018-04-04-ogp-json/

まず認証情報を作るところがなかなか面倒です。こちらのURLがほぼまんま参考になるので順を追って実施してみてください(丸投げ)。

https://liginc.co.jp/356517

jsonを取得してGoogle Analytics側にjsonの中に書いてあるメールアドレスをユーザーとして追加するところまでやっておきます。

次にコードを書きます。

まずは依存するライブラリを追加します。(Echoのコードはすでにある前提とします。

% dep ensure -add golang.org/x/oauth2
% dep ensure

そしてimportに追加

import (
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	analytics "google.golang.org/api/analytics/v3"
)

Echoに新しいルーティングを追加します。

func main() {
	e.GET("/ga", getGA)
}

ハンドラはこんな感じ。こちらをかなり参考にさせてもらいました。

http://blog.soushi.me/entry/2016/11/07/152046
func getGA(ctx echo.Context) error {
	client, err := google.DefaultClient(
		oauth2.NoContext,
		"https://www.googleapis.com/auth/analytics.readonly")
	if err != nil {
		return ctx.String(http.StatusInternalServerError, fmt.Sprintf("Unable to read client : %s", err.Error()))
	}

	service, err := analytics.New(client)
	if err != nil {
		return ctx.String(http.StatusInternalServerError, fmt.Sprintf("Unable to Access Google Analytics: %s", err.Error()))
	}

	result, err := service.Data.Ga.Get("ga:xxxxxxxxxx", "7daysAgo", "today", "ga:pageviews").Dimensions("ga:pagePath,ga:pagePathLevel1,ga:pagePathLevel2,ga:pageTitle").Filters("ga:pagePath=~^/posts/").Sort("-ga:pageviews").Do()
	if err != nil {
		return ctx.String(http.StatusInternalServerError, fmt.Sprintf("Unable to get data: %s", err.Error()))
	}

	return ctx.JSON(http.StatusOK, result)
}

ga:xxxxxxxxxxとなっている箇所はGoogle AnalyticsのViewに対応しています。

また、コードの14行目のあたりでDimensionやらFilterやらSortやらを指定しています。これらはQuery Explorerで確認して決めると便利です。

https://blog.piyo.tech/posts/2018-05-21-google-analytics-query-explorer/

これでコードはOKです。実行時に先ほどのjsonファイルが必要となります。環境変数での指定が必要なので、GOOGLE_APPLICATION_CREDENTIALS=path/to/jsonのような形で実行してあげると、無事Echo経由でGoogle AnalyticsのAPI呼び出しをJSONで取得できるようになりました。