LoginSignup
0
0

More than 1 year has passed since last update.

Ginでサーバーを立ち上げてJSONのメッセージを表示

Posted at

概要

Ginでサーバーを立ち上げてJSONのメッセージを表示させる。

環境

・Docker
・MacBook

docker run でgolamgが入ったコンテナを作る。

~/d/q/gin_server ❯❯❯ docker run -itd --name gin_server -p 8080:80 golang:latest

#コンテナにはいる
~/d/q/gin_server ❯❯❯ docker attach gin_server
Docker
root@1cc8cba550f2:~# cd ../root

#Vimをインストールする
root@1cc8cba550f2:~# apt update
root@1cc8cba550f2:~# apt install vim

#Vimで空のmain.goを作る
root@1cc8cba550f2:~# vim main.go

#ginをダウンロードする
root@1cc8cba550f2:~# go get github.com/gin-gonic/gin
go: downloading github.com/gin-gonic/gin v1.7.4

root@1cc8cba550f2:~# go mod init example.com/m

コーディング

main.go
package main

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

func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run(":80")
}

go mod vendorする

Docker
root@1cc8cba550f2:~# go mod vendor
go: finding module for package github.com/gin-gonic/gin
go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.7.4

main.goを起動する

root@1cc8cba550f2:~# go run main.go

ブラウザからlocalhostにアクセスする

画面に下記のように表示されたら成功

{
message: "pong"
}
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