0
0

Go言語のGinフレームワークで静的ファイルを表示してみた

Posted at

Go言語のGinフレームワークで静的ファイルを表示してみた

現実味がありすぎると良くないことありますよね

 いやー。空想は空想でいいんですよ?

 でも現実を謳っていて、現実味が欠けていると、ちょっとなあ、て思う時があります。

 
 まあいいんですけどね。

結局は変わらないものが良いんですよね。

目次

1. Ginフレームワークとは

 Ginは、Golangで書かれたWebフレームワークです。

 martiniに似たAPIを持ちながら、非常に優れたパフォーマンスを発揮し、最大で40倍高速であることが特徴です。

 martini(マティーニ)はGo言語で書かれたWebフレームワークで、モジュラー設計と使いやすさが特徴ですが、パフォーマンスの問題と非標準API設計により議論を呼んでいます。

詳しくは下記のサイトに。

参考
gin フレームワーク公式

2. コード例

main.goのコード例

 ここではred.html、blue.html、yellow.htmlの三つを表示させます。

ファイル構造は以下のようになります。

ls
> go.mod  go.sum main.go public

ls public
> blue.html  red.html  yellow.html
main.go
import (
	"github.com/gin-gonic/gin"
)

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

	// 静的ファイルのルートを追加
	engine.StaticFile("/red", "./public/red.html") // publicディレクトリ内のred.htmlを提供
	engine.StaticFile("/blue", "./public/blue.html") // publicディレクトリ内のblue.htmlを提供
	engine.StaticFile("/yellow", "./public/yellow.html") // publicディレクトリ内のyellow.htmlを提供

	engine.Run(":" + "8080")
}

htmlのコード例(red.html)
 htmlを試しに書いてみます。

<!DOCTYPE html>
<html>
<head>
   <tile>Red Page</tile>
</head>
<body style="background-color: red;">
   <h1>Welcome to the Red Page!</h1>
</body>
</html>

 実行してみると

go mod init static
go get -u github.com/gin-gonic/gin
go build 
./static  //実行ループ

 立ち上がったので、ブラウザで

http://localhost:8080/red

と検索してみると以下のようなサイトが表示されます。

Screenshot 2024-02-10 at 23.13.47.png

3. おわりに

 意外とGinではGETとかPOSTの処理ばかりやるので、静的ファイルについて学んでみました。

 ここから先の、CSSとかあまり詳しくないので色々と遊んでみたいなと思いました。

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