0
0

More than 3 years have passed since last update.

go:mapstructureを使ってJSONファイルを開いて構造体を返す汎用的な関数

Last updated at Posted at 2020-03-07

やりたいこと

  • いろんなファイルを読み込む必要がある
  • いちいちそのファイル専用の関数を作りたくない
  • JSONファイルパスと構造体を渡すだけで済む汎用的な関数を作りたい

コード

config.json
{
  "ip_addresses": ["127.0.0.1", "127.0.0.2", "127.0.0.3"]
}
main.go
package main

import (
  "fmt"
  "github.com/mitchellh/mapstructure"
  "encoding/json"
  "io/ioutil"
)

type Conf struct {
  // ここ重要。アンダースコア必要
  Ip_Addresses     []string `json:"ip_addresses"`
}

func main() {
  const confPath = "./config.json"
  var conf Conf
  convertJsonFileToStruct(confPath, &conf)
  fmt.Print(conf.Ip_Addresss)
}

func convertJsonFileToStruct(filePath string, resultReceiver interface{}) {
  // JSONファイル読み込み
  file, err := ioutil.ReadFile(filePath)
  if err != nil {
    panic(err)
  }

  // JSON化
  dynamicJson := make(map[string]interface{})
  if err := json.Unmarshal([]byte(file), &dynamicJson); err != nil {
    panic(err)
  }

  // 引数でもらった構造体にmapstructureを使ってJSONを入れる
  if err := mapstructure.Decode(dynamicJson, &resultReceiver); err != nil {
    panic(err)
  }
}

補足

  • 貰った構造体とJSONの構造が一致しないとちゃんとエラーになってくれる
  • なぜ構造体のフィールド名にアンダースコアがなければいけないのかはまだ調べられていない
  • アンダースコアが無いとエラーにならない&値取れないので注意

感想

  • ポインター便利だけど飛び道具感ある
  • interface戸惑う
  • goって薄くする文化らしくてそのせいか「この処理はこれ!」みたいなデファクトスタンダードなパッケージがあまり無い印象。ガンガン使った方が生産性高くない?(Rails脳)
    • 中国のgopherはフルスタックのbeegoをガンガン使ってて合理的な印象がある
    • 性能を追い求めてピュアにするぐらいならCの方が良いのでは?誰かに話を聞いてみたい
      • 追記:知り合いの大先生曰く「Cはメモリの扱いが難しいのでその観点でgoを使うのは妥当」とのことでした
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