LoginSignup
5
5

Go入門 : Go(Gin)で簡単にWebサーバーを作ってみる

Last updated at Posted at 2024-05-09

はじめに

Go言語でWebサーバーを立てる方法について、学習のメモとしてまとめていきます。

・version : go 1.22.2

Webサーバーを実装

まず初めに、下記のコマンドでmoduleの初期化を行います。

go mod init モジュール名

go.modファイルが作成されます。

次に、下記のコマンドでmain.goのファイルを作成します。

touch main.go

最初に、Hello Golang!! を出力するcodeをmain.goに記述してみましょう。

main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello Golang!!")
}

記述後、下記のコマンドで Hello Golang!! が出力されるか確認しましょう。

go run main.go

Hello Golang!! が出力されればOKです。

Ginを導入する

下記の公式Docsを参考に、Ginを導入していきます。

Gin Web Framework

main.goを下記のように修正します。

main.go
package main

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

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

その後、下記のコマンドを入力します。

go mod tidy

go mod tidyを実行することで、Goモジュールの依存関係を最新の状態にします。

それでは、main.goを実行します。

go run main.go

ターミナル上で、下記のように出力されればOKです。

$ go run main.go     
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /hoge                     --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

次に、別のターミナルを開いて、下記のコマンドを入力します。

curl http://localhost:8080/hoge

下記のように出力されれば完成です。

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