0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめてのGo

Last updated at Posted at 2022-08-06

まずはGoのInstallから

とりあえずGinというフレームワークでREST APIを作る想定で学習してみよう。

目次

  1. GoのInstall
  2. GinのInstall
  3. コードを書く
  4. APIを実行してみよう

GoのInstall

MacならbrewでInstall可能

taka$ brew install go

ちゃんとInstall出来たか確認しよう

taka$ go version
go version go1.18.5 darwin/amd64

パスの設定がうまくいっているか確認しよう

taka$ go env GOROOT
/usr/local/Cellar/go/1.18.5/libexec

taka$ go env GOPATH
/Users/taka/go

GinのInstall

GOPATHに合わせてディレクトリを作成する

taka$ mkdir go
taka$ cd go
taka$ mkdir test-gin
taka$ cd test-gin/
taka$ go mod init test-gin
taka$ go get -u github.com/gin-gonic/gin

コードを書く

エンドポイントの設定とレスポンスを返す関数を作成してみよう
https://github.com/oretanegi/test-gin/blob/master/main.go
(サンプルは公開していますので、こちらでもどうぞ

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func home(c *gin.Context) {
	// :nameから値を取り出す
	name := c.Params.ByName("name")
	c.JSON(200, gin.H{
		"message": fmt.Sprintf("hello %s", name),
	})
}

func instruments(c *gin.Context) {
	var instruments [3]string
	instruments[0] = "piano"
	instruments[1] = "guitar"
	instruments[2] = "bass"

	c.JSON(200, gin.H{
		"message": instruments,
	})
}

func games(c *gin.Context) {
	var games [2]string
	games[0] = "BanG Dream!"
	games[1] = "ragnarokorigin"

	c.JSON(200, gin.H{
		"message": games,
	})
}

func main() {
	router := gin.Default()

	router.GET("/:name", home)
	router.GET("/instruments", instruments)
	router.GET("/games", games)

	router.Run(":5000")
}

APIを実行してみよう

サーバを起動?

taka$ go run main.go

curlでアクセスしてみよう

taka$ curl -X GET localhost:5000/instruments
{"message":["piano","guitar","bass"]}

TypeScriptを覚えるよりは楽かも知れない。。。
(一応、C言語経験者ですし

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?