最近Go言語を使ってjsonファイルを読み込んで表示してみました。本記事ではその方法について紹介します。最近はアプリケーションをコンテナで実行しているので、コンテナベースでの実行とします。
- jsonファイルを作成する
- jsonファイルを読み込んで出力するソースコードを作成する
- コンテナで実行して出力を確認する
1. jsonファイルを作成する
用意したjsonファイル(categories.json)を以下に示します。jsonらしくはない、ただの配列になってますが。。
{
"categories": [
{ "name": "スポーツ" },
{ "name": "文化" },
{ "name": "娯楽" },
{ "name": "食事" },
{ "name": "お酒" },
{ "name": "イベント" },
{ "name": "ドライブ" },
{ "name": "文化" }
]
}
2. jsonファイルを読み込んで出力するソースコードを作成する
Goのソースコード(main.go)を以下に記します。public関数がjsonファイルを読み込んで表示する処理を行います。注意点としては、jsonファイルを読み込む時に構造体を利用することです。ここでは、postという構造体を定義していて、categories.jsonの形式に合わせています。json.Unmarshal(categories, &output)が構造体postの変数であるoutputに対して、jsonファイルから取得した内容を代入しています。
package main
import (
"encoding/json"
"fmt"
"searcher/data"
"log"
"net/http"
"github.com/gorilla/mux"
"io/ioutil"
"os"
)
type post struct {
Categories []struct{
Name string `json:"name"`
}`json:"categories"`
}
func main() {
r := mux.NewRouter()
// localhost:8082/publicでpublicハンドラーを実行
r.Handle("/public", public)
//サーバー起動
if err := http.ListenAndServe(":8082", r); err != nil {
log.Fatal("ListenAndServe:", nil)
}
}
var public = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//Jsonファイルの読み込み
categories, err := ioutil.ReadFile("./data/categories.json")
if err != nil {
fmt.Println(err.Error())
}
var output post
if err := json.Unmarshal(categories, &output); err != nil {
log.Fatal(err)
os.Exit(1)
}
//読み込んだJsonの表示
json.NewEncoder(w).Encode(output)
})
3. コンテナで実行してJsonの表示を確認する
ビルド用ディレクトリ構造は以下の通りです。
$ tree .
.
├── Dockerfile
└── src
├── categories.json
└── main.go
Dockerfileは以下の通りです。
FROM golang:latest
WORKDIR /go/src/searcher
COPY ./src .
RUN go get -u github.com/gorilla/mux
RUN go build -o searcher
CMD ["./searcher"]
以下のコマンドでビルドします。
$ docker build -t test:latest .
Sending build context to Docker daemon 19.46kB
Step 1/6 : FROM golang:latest
---> 2421885b04da
Step 2/6 : WORKDIR /go/src/searcher
---> Using cache
---> 588d44459848
Step 3/6 : COPY ./src .
---> e863f9711371
Step 4/6 : RUN go get -u github.com/gorilla/mux
---> Running in a66f5891cc12
Removing intermediate container a66f5891cc12
---> 7a098828debd
Step 5/6 : RUN go build -o searcher
---> Running in 79cf40f885b3
Removing intermediate container 79cf40f885b3
---> 78cef5ba6945
Step 6/6 : CMD ["./searcher"]
---> Running in 03373a52a96a
Removing intermediate container 03373a52a96a
---> 47e4f7d48325
Successfully built 47e4f7d48325
Successfully tagged test:latest
$ docker images test
REPOSITORY TAG IMAGE ID CREATED SIZE
test latest 47e4f7d48325 5 minutes ago 819MB
以下のコマンドでコンテナを実行し、出力を確認します。
$ docker run -d --name test -p 8082:8082 test
8f8b34416854890b1cd527a2f40b93758d289a59db79c8c46559ad3a2d48265e
$ curl localhost:8082/public
{"categories":[{"name":"スポーツ"},{"name":"文化"},{"name":"娯楽"},{"name":"食事"},{"name":"お酒"},{"name":"イベント"},{"name":"ドライブ"},{"name":"文化"}]}