LoginSignup
51
42

More than 3 years have passed since last update.

go-ginでサクッとRESTAPIを構築する

Last updated at Posted at 2019-07-07

ginとは

ginは、Go言語のフレームワークの中においてメジャーで歴史あるフレームワークで、軽量かつシンプルなインターフェイスが特徴です。

今回はそんなginを使って、簡単なRESTAPIを構築していきます。

ginを導入

go getで。

 go get -u github.com/gin-gonic/gin

公式githubサンプルを動かしてみましょう。

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}
go run main.go

http://localhost:8080/ping へアクセスしてみてください。
message":"pong"と表示されています。

r := gin.Default()

こちらの処理でデフォルトのミドルウェアで新しいルーターを作っています。

RESTAPIの構築

それでは新しく、RESTAPIを構築していきます。
サンプルとして作るのは、タイトルとディスクリプションだけ持ったArticleをPOST,GETできる機能になります。

またディレクトリ構造は下記になります。

src
┣article 
┃   ┗article.go
┃
┗httpd
 ┣handler
 ┃ ┗articleFunc.go   
 ┗main.go

まずはArticleを定義します。
書いてある通りですね。

article.go
package article

type Item struct {
    Title       string `json:"title"`
    Description string `json:"description"`
}

type Articles struct {
    Items []Item
}

func New() *Articles {
    return &Articles{}
}

func (r *Articles) Add(item Item) {
    r.Items = append(r.Items, item)
}

func (r *Articles) GetAll() []Item {
    return r.Items
}

続いて上記ファイルで定義したArticleのfunctionをまとめたファイルです。
こちらもそのままな処理ですね。

articleFunc.go

package handler

import (
    "net/http"

    "restAPI/article"

    "github.com/gin-gonic/gin"
)

func ArticlesGet(articles *article.Articles) gin.HandlerFunc {
    return func(c *gin.Context) {
        result := articles.GetAll()
        c.JSON(http.StatusOK, result)
    }
}

type ArticlePostRequest struct {
    Title       string `json:"title"`
    Description string `json:"description"`
}

func ArticlePost(post *article.Articles) gin.HandlerFunc {
    return func(c *gin.Context) {
        requestBody := ArticlePostRequest{}
        c.Bind(&requestBody)

        item := article.Item{
            Title:       requestBody.Title,
            Description: requestBody.Description,
        }
        post.Add(item)

        c.Status(http.StatusNoContent)
    }
}

最後はメインとなるmain.goです。

main.go
package main

import (
    "restAPI/httpd/handler"

    "restAPI/article"

    "github.com/gin-gonic/gin"
)

func main() {
    article := article.New()
    r := gin.Default()
    r.GET("/article", handler.ArticlesGet(article))
    r.POST("/article", handler.ArticlePost(article))

    r.Run() // listen and serve on 0.0.0.0:8080

}

ここまで構築をしたら下記で起動してみてください

go run httpd/main.go

http://localhost:8080/article
へのPOSTとGETが利用できるようになっているはずです。

試しにPostmanを用いて行ってみます。

POST(HeadersにContent-Type:application/jsonを設定)
Screen Shot 2019-07-08 at 12.35.47 AM.png

GET
Screen Shot 2019-07-08 at 12.35.57 AM.png

以上になります。

参考資料

https://github.com/gin-gonic/gin
https://gin-gonic.com/ja/docs/

51
42
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
51
42