Loading

gin环境&路由配置&模版渲染

Gin 是一个 Go (Golang) 编写的轻量级 http web 框架,运行速度非常快

Gin 的官网:https://gin-gonic.com/zh-cn/

Gin Github 地址:https://github.com/gin-gonic/gin

gin环境搭建

  1. 下载并安装
# go mod 同级目录下
go get -u github.com/gin-gonic/gin                           
  1. 引入gin
import  "github.com/gin-gonic/gin"

  1. 配置路由
package main

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

func main() {
	// 创建一个默认路由引擎
	router := gin.Default()
	// 配置路由
	/*
			func(c *gin.Context) 是一个函数签名,回调方法,用于定义 Gin 框架中的路由处理函数
		    gin.Context 是 Gin 框架中的上下文对象,它封装了当前 HTTP 请求的所有信息,包括请求头、请求参数、路径等。
		    通过在路由处理函数中接收 c *gin.Context 参数,我们可以获取和操作请求的相关信息,以及向客户端发送响应
	*/
	router.GET("/", func(c *gin.Context) {
		// 响应一个字符串数据,code200, 内容是msg:ok
		c.String(200, "msg:ok")

	})

	/*
		Run方法参数:
		addr: 可选参数,表示服务器要监听的地址和端口
		它是一个可变参数,可以传入多个地址和端口的组合。如果未提供参数,则默认监听在 :8080端口,默认地址是0.0.0.0
	*/
	// 启动web服务
	router.Run() // 0.0.0.0:8080
	// router.Run(":8081") // 指定8081端口,0.0.0.0:8081
	// router.Run("127.0.0.1:8080") // 监听在指定地址 127.0.0.1:8080 上
  1. 运行项目

    go run main.go
    

golang热加载

热加载就是当我们对代码进行修改时,程序能够自动重新加载并执行,可以快速进行代码测试,省去了每次手动重新编译,gin 中并没有官方提供的热加载工具,需要使用第三方的工具

  1. 安装 fresh到go环境

    go install github.com/pilu/fresh@latest
    
  2. 下载fresh

    go get github.com/pilu/fresh   
    
  3. 使用fresh启动服务

    第一次使用fresh启动会在项目目录下创建tmp文件

    # fresh 代替go run main.go
    fresh
    

Gin框架的路由

net/http

net/http 包定义了各种状态码常量

import (
	"github.com/gin-gonic/gin"
	"net/http"
)
// 路由
router.GET("/", func(c *gin.Context) {
		// http.statusOk == 200
		c.JSON(http.StatusOK, "msg:ok")

	})
响应string数据
	router.GET("/str", func(c *gin.Context) {
		// 响应一个字符串数据,format是一个字符串
		c.String(http.StatusOK, "msg:ok")

	})
响应json数据
// 方式一
router.GET("/json", func(c *gin.Context) {
		// 响应一个json数据,format是一个空接口类型
		c.JSON(http.StatusOK, map[string]interface{}{"success": true, "msg": "访问成功"})
	
	})
// 方式二
	router.GET("/json", func(c *gin.Context) {
		// 响应一个json数据,format是一个空接口类型
		c.JSON(http.StatusOK, gin.H{"success": true, "msg": "访问成功"})

	})

/* 
gin.H 就是框架定义好的map格式
// H is a shortcut for map[string]any
type H map[string]any

*/
返回结构体
	router.GET("/s", func(c *gin.Context) {
		s := Article{
			Title:"t",
			Desc:"描述",
		}
		c.JSON(http.StatusOK, s)

	})
返回JSONP

主要用来解决跨域问题

	router.GET("/jsonp", func(c *gin.Context) {
		s := Article{
			Title: "t1",
			Desc:  "描述",
		}
		c.JSONP(http.StatusOK, s)

	})

image-20240226115910150

返回xml数据
	router.GET("/xml", func(c *gin.Context) {
		c.XML(http.StatusOK,gin.H{"success":true,"msg":"ok"})

	})
渲染模版
	// 加载模版文件,templates目录下的所有
	router.LoadHTMLGlob("./templates/*")
	router.GET("/html", func(c *gin.Context) {
		
		c.HTML(http.StatusOK, "index.html", gin.H{"title": "后台标题"})

	})
<body>
    <h2>{{.title}}</h2>

</body>
模版在不同目录渲染

模板放在不同目录

目录结构

image-20240226133900126

模版定义

使用define给模版定义一个名字,define和end成对出现,define 和 end 之间的,使用default/news.html渲染

{{ define "default/news.html" }}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h2>{{.title}}</h2>
    <p>{{.news.Title}}</p>
    <p>{{.news.Desc}}</p>

</body>
</html>

{{ end }}
路由配置
package main

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

type Article struct {
	Title string
	Desc  string
}

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

	// 加载模版文件,**代表一层目录,templates下的目录下的所有模版
	router.LoadHTMLGlob("./templates/**/*")

	// 模版首页
	router.GET("/", func(c *gin.Context) {
		// 渲染 define 的admin/index.html
		c.HTML(http.StatusOK, "admin/index.html", gin.H{"title": "首页"})

	})

	router.GET("/news", func(c *gin.Context) {
		// Article 结构体
		news := Article{Title: "新闻标题", Desc: "新闻内容"}
		// 渲染define 的default/news.html
		c.HTML(http.StatusOK, "default/news.html", gin.H{"title": "新闻页面", "news": news})

	})

	router.Run()
}

posted @ 2024-02-26 13:13  木子七  阅读(17)  评论(0编辑  收藏  举报