0
0

Go REST API を作ってみる

Posted at

GoでREST APIを作成する :baby_tone2:

下準備

mkdir todo-go
cd todo-go

プロジェクト作成

go mod init example/todo-go

パッケージ追加

go get github.com/gin-gonic/gin

実行

go run .

postmanの結果
image.png

ソースコード

package main

import (
	"net/http"

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

type todo struct {
	ID        string `json:"id"`
	Item      string `json:"title"`
	Completed bool   `json:"completed"`
}

var todos = []todo{
	{ID: "1", Item: "Goの言語仕様を学習する", Completed: false},
	{ID: "2", Item: "Goのチュートリアルを実践する", Completed: false},
	{ID: "3", Item: "Goで動くアプリを開発する", Completed: false},
	{ID: "4", Item: "QiitaにGoに関するアウトプットを行う", Completed: false},
}

func getTodos(context *gin.Context) {
	context.IndentedJSON(http.StatusOK, todos)
}

func main() {
	router := gin.Default()
	router.GET("/todos", getTodos)

	router.Run("localhost:8080")
}

Reference

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