前提
プログラミング初心者です。
練習でGoとVueを使ったwebアプリケーションのフロントエンド部分を作成しているときにエラーが発生して困っています。
具体的には、下記「該当のソースコード」に記載のHTMLファイルが表示されるようにしてwebサーバを起動しようとすると、エラーが発生してwebサーバの起動に失敗します。
実現したいこと
- webサーバを正常に起動できるようにする
- jsから正常にhtmlに値を渡せるようにする
発生している問題・エラーメッセージ
※「message」が表示されてほしい文字列が入る変数です
PS C:\Users\***\Go\***> 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) panic: template: index.html:20: function "message" not defined goroutine 1 [running]: html/template.Must(...) C:/Program Files/Go/src/html/template/template.go:368 github.com/gin-gonic/gin.(*Engine).LoadHTMLGlob(0xc0000849c0, {0x88f8ac, 0xc}) C:/Users/***/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:251 +0x306 main.serve() C:/Users/***/Go/***/main.go:14 +0x33 main.main() C:/Users/***/Go/***/main.go:53 +0x17 exit status 2
特に
panic: template: index.html:20: function "message" not defined
の部分です。
フォルダ構成
C:.
app
│ .gitignore
│ go.mod
│ go.sum
│ main.go
│
├─controllers
│□□Controller.go
│
├─models
│ ├─db
│ │□□ UserDb.go
│ │
│ └─entity
│□□□□ User.go
│
└─views
□□├─html
□□│□□index.html
□□│
□□└─js
□□□□test.js
該当のソースコード
index.html
html
1<!DOCTYPE html> 2<html> 3 <body> 4 <!--CDNによるVueの取り込み --> 5 <script src="https://unpkg.com/vue@next"></script> 6 7 <!--Vueインスタンスの生成--> 8 <script> 9 new Vue({ 10 el: "#show", 11 data() { 12 return { 13 message: "Hello Vue!" 14 }; 15 } 16 }); 17 </script> 18 19 <!--messageの表示--> 20 <div id="show"> 21 Message: {{ message }} 22 </div> 23 24 </body> 25</html>
main.go
go
1package main 2 3import ( 4 "net/http" 5 "app/controllers" 6 7 "github.com/gin-gonic/gin" 8) 9 10func serve() { 11 12 r := gin.Default() 13 14 r.LoadHTMLGlob("views/html/*") 15 16 r.GET("index", func(ctx *gin.Context) { 17 ctx.HTML(http.StatusOK, "index.html", gin.H{ 18 "title": "Main Page", 19 }) 20 }) 21 22//ルーティングについては記載を省略 23 24 r.Run(":8888") 25} 26 27func main() { 28 29 serve() 30 31}
期待していた動作
html
1 <!--messageの表示--> 2 <div id="show"> 3 Message: {{ message }} 4 </div>
この {{ message }}に、
html
1 <!--Vueインスタンスの生成--> 2 <script> 3 new Vue({ 4 el: "#show", 5 data() { 6 return { 7 message: "Hello Vue!" 8 }; 9 } 10 }); 11 </script>
ここで設定したmessageが入るという動作を期待していました。
試したこと
index.htmlが以下の場合には正常にwebサーバが起動し、「localhost:8888/index」にアクセスすることでindex.htmlが表示されます。
html
1<!DOCTYPE html> 2<html> 3 <h1>Hello Gin!</h1> 4</html>
よろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/09/14 15:23