Golang 中 Gin 框架开发学习记录 ——(二)

发布时间 2023-07-21 23:32:39作者: 想成为编程高手的阿曼

4、响应页面

    首先创建 template 文件夹将需要的 hmtl 文件放在里面,然后编写 hmtl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的GO web页面</title>

    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/commom.js"></script>
</head>
<body>

<h1>hello world!</h1>

后端的数据为
{{.msg}}

</body>
</html>

设置标题为 “我的 GO web 页面”,输出为 "hello world",并且接收后端数据(只会编写)

然后同样的,先创建一个服务,并设置一个服务器接口

	//创建一个服务
	ginServer := gin.Default()
	ginServer.Use(favicon.New("./aevr4-fg4ao-001.ico"))


	//服务器端口
	ginServer.Run(":8081")

然后就可以在中间设置我们的服务了,先是加载静态页面

	//加载静态页面
	ginServer.LoadHTMLGlob("templates/*")

 接着利用 Gin 的 Restful 获取后端数据并输出

	//Gin Restful
	ginServer.GET("/hello", func(context *gin.Context) {
		//context.JSON(200, gin.H{"msg": "hello,world"})返回JSON数据
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "这是后台传来的数据",
		})
	})

这样一个基本的页面响应就做好了,如果要想美化一下页面可以设置 static 文件夹放入 css 和 js 文件进行美化这里的 css 和 js 分别写为

body{
    background: aquamarine;
}
alert(1)

并在 main 文件中进行相关设置

	//加载资源文件
	ginServer.Static("/static", "./static")

以上合起来就可以完成一个完整的页面响应了

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/thinkerou/favicon"
	"net/http"
)

func main() {
	//创建一个服务
	ginServer := gin.Default()
	ginServer.Use(favicon.New("./aevr4-fg4ao-001.ico"))
	//加载静态页面
	ginServer.LoadHTMLGlob("templates/*")

	//加载资源文件
	ginServer.Static("/static", "./static")

	//Gin Restful
	ginServer.GET("/hello", func(context *gin.Context) {
		//context.JSON(200, gin.H{"msg": "hello,world"})返回JSON数据
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "这是后台传来的数据",
		})
	})
	//响应一个页面给前端

	//服务器端口
	ginServer.Run(":8081")
}