0
点赞
收藏
分享

微信扫一扫

gin框架学习

文章目录

一、 加载静态文件

package main

import (
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
)
func main() {
	g :=gin.Default()
	//加载静态文件
	g.Static("../statics","../statics")
	//gin框架中给模板添加自定义函数
	g.SetFuncMap(template.FuncMap{
     "safe":func (str string) template.HTML {
		 return template.HTML(str)
	 },
	})

	//	模板解析
	//渲染一个文件loadHTMLFiles   渲染多个模板 g.loadHTMLGlob("temp/**/*")
	g.LoadHTMLFiles("../temp/index.tmpl")
	g.GET("/index", func(c *gin.Context) {
		//模板渲染
		c.HTML(http.StatusOK,"index.tmpl",gin.H{
			"title" : "MaJing.com",
		})
	})
//	启动
    g.Run(":8080")
}

二、传递json

package main

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

func main() {
	r := gin.Default()
	//r.GET("/json", func(c *gin.Context) {
	//	//法1:使用map
	//   c.JSON(http.StatusOK,gin.H{
	//   	  "name":"猪八戒",
	//   	  "age":"600",
	//   	  "skill":"泰山压顶",
	//   })
   //})
    //   法2:使用结构体
    //注:必须大写
     type People struct{
     	Name string  `json:"name"`  //tag 来做定制操作  反射
     	Age  int
     	Skill string
	 }
	 r.GET("/json", func(c *gin.Context) {
	 	date:=People{
	 		"孙悟空",
	 		800,
	 		"火眼金睛",
		}
		 c.JSON(http.StatusOK,date)
	 })
	r.Run(":8080")
}

三、 获取搜索栏的querystring字符串

package main

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

//  https://www.baidu.com?query=杨超越?  之后是query数据  键值对类型

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

	r.GET("/web", func(c *gin.Context) {
    //获取浏览器那边携带的query string 参数
	//	key_value格式,多个key——value格式用&连接
	//	name := c.Query("query") //通过query获取
	//	如果能在浏览器中获取到query,就是query 。如果没有,使用默认的
	//	name :=c.DefaultQuery("query","小王子")
		name, _ := c.GetQuery("query")//取不到第二个参数就返回FALSE
		c.JSON(http.StatusOK,gin.H{
			"name":name,
		})
	})

	r.Run(":8080")
}

在这里插入图片描述
在这里插入图片描述

举报

相关推荐

0 条评论