LoginSignup
3
0

More than 1 year has passed since last update.

【Golang】gqlgen、gin、GORMを使ったプロジェクトテンプレート

Last updated at Posted at 2022-03-05

はじめに

Goの学習のためgin、gqlgen、GORMを使ってGraphQLのAPIを作成しました。
備忘のためにプロジェクトのテンプレートとその説明を残します。

作成したテンプレートは以下に公開しています。

環境

プロジェクト解説

構成

プロジェクトの構成は以下の通りです。

├─db
│  ├─db.go
│  └─dbconfig.ini
├─graph
│  ├─generated
│  │  └─generated.go
│  ├─model
│  │  ├─models_gen.go
│  │  └─todo.go
│  ├─resolver.go
│  ├─schema.graphqls
│  └─schema.resolvers.go
├─router
│  └─router.go
├─go.mod
├─gqlgen.yml
└─server.go
  • db
    db関連のファイルを入れています。
    dbconfig.iniにDB接続設定を定義します。環境に合わせて編集します。
    postgreSQL以外を使用する場合はそれに合わせたドライバーをインストールします。
    db.goでgormでのDBオブジェクトの作成、DB接続、マイグレーションを行います。

  • graph
    gqlgenの以下コマンドで自動作成されるgraphql関連の(model、shcema、resolver)の定義ファイル

    go run github.com/99designs/gqlgen init
    

    model、schema.resolvers.goあたりを修正していきます。

  • router
    Ginを使ってルーティングを定義しています

  • server.go
    プロジェクトのエントリーポイント。
     Webサーバ、DBの初期化、起動を行います。

使用方法

依存パッケージの読み込み

以下のコマンドを実行して依存パッケージを取り込みます。

go mod tidy

実行後はgo.sumというファイルが出来ます。

サーバ起動

go run server.go

サーバが起動します。
デフォルトではhttp://localhost:8000/queryでgraphQLでのリクエストを受け付けます。
何か適当にクライアントを用意してリクエストすると、Todoデータの作成、取得が行えます。

fetchAPIを使って確認したコードは以下の通りです。

  • todoデータ作成
fetch("http://localhost:8000/query",{
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    query: `
      mutation createTodo {
        createTodo(input: { text: "todo", userId: "2" }) {
          text
          done
          userId
        }
      }
     `
    })
  })
  • todoデータ取得
fetch("http://localhost:8000/query",{
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    query: `
      query findTodos {
          todos {
            text
            done
            userId
          }
        }
    `
  })
})

おわりに

簡単ですが以上となります。
基本的にはgqlgenで初期化したプロジェクト構成をベースにして、gin,gormを導入したような構成になっています。
今後も何か改善したらレポジトリを更新していこうと思います。

3
0
1

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
3
0