对Gin框架的学习(代码说明)

模板渲染

package main

import (
	"fmt"
	"html/template"
	"net/http"
)


func f1(w http.ResponseWriter,r *http.Request){
	//定义模板
	//解析末班
	t := template.New("f.tmpl")
	_,err:=t.ParseFiles("./f.tmpl")
	if err != nil{
		fmt.Printf("failed! err:%v",err)
		return
	}
	//渲染模板
	name:="小王子"
	t.Execute(w,name)
}

func main() {
	http.HandleFunc("/",f1)
	err:=http.ListenAndServe(":9023",nil)
	if err != nil{
		fmt.Printf("failed! err:%v",err)
		return
	}
}

四种请求及对应写法

package main

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

func runfunc(c *gin.Context){//参数必须是Context
	c.JSON(200,gin.H{ //200是http状态响应码
		//gin.H理解成为一个JSON格式的
		"message": "hello golang/gin!",//前者是key,后者是value

	})//返回的是一个JSON的数据格式

}

func main (){
	r:=gin.Default()//返回默认的路由引擎

	r.GET("/book", func(context *gin.Context) {
		context.JSON(200,gin.H{
			"GETname":"CloudyTenderness",
		})
	}) //基于http协议 的get方法  ---------用户访问我/hello的时候,我去执行runfunc这个函数

	r.POST("/book", func(context *gin.Context) {
		context.JSON(200,gin.H{
			"POSTarea":"black rose",
		})
	})//创建一个
	r.PUT("/book", func(context *gin.Context) {
		context.JSON(200,gin.H{
			"PUT你":"您",
		})
	})//更新一个
	r.DELETE("/book", func(context *gin.Context) {
		context.JSON(http.StatusOK,gin.H{// =200
			"DELETE":"what",
		})
	})//删除一个

	//启动服务
	r.Run(":9090") //若改变端口,就用这个里面加上 ":9090"
}


 自定义表单判断

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
)
//mustBig 是一个自定义的表单判断(比如说是年龄有没有满足条件)
type posttest struct{
	Name string `json:"name" uri:"name" form:"name"`
	Age int `json:"age"  binding:"required,mustBig"` //binding 声明一个func,进而让我们进行自定义筛选格式(mustBig)
	Sex bool `json:"sex" uri:"sex" form:"sex"`
}

func mustBig (fl validator.FieldLevel)bool{ //自定义表单函数定义!  ----使用方式在 main 的 第二行if函数中
	if fl.Field().Interface().(int) <18 {// ------通过反射的形式将内容(age-int)表现出来,进而方便我们进行比较
		return false
	}
	return true
}

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

	if v,ok:=binding.Validator.Engine().(*validator.Validate);ok{//进行断言
		v.RegisterValidation("mustBig",mustBig)//注册验证规则 --加标签和--加函数--
	}


	r.GET("/cloud:id", func(c *gin.Context) {
		id:=c.Param("id")
		user:=c.Query("user")
		cat:=c.Query("cat")
		c.JSON(http.StatusOK,gin.H{
			"weather":"cloudy",
			"id":id,
			"user":user,
			"cat":cat,
		})
	})
	r.POST("/cloud_json", func(c *gin.Context) {//在上面结构体中绑定时要用:
		//Name string `json "name"`

		var g posttest
		err:=c.ShouldBindJSON(&g)
		if err!=nil{
			c.JSON(200,gin.H{
				"msg":"error!123",
			})
		}else {
			c.JSON(200,gin.H{
				"msg":"success!",
				"data":g
			})
		}
	})
	r.POST("/cloud_uri/:name/:age/:sex", func(c *gin.Context) { //在上面的结构体里面要记得绑定:
		//绑定成为: Name string `json:"name" uri:"name"`
		var g posttest
		err:=c.ShouldBindUri(&g)
		if err!=nil{
			c.JSON(200,gin.H{
				"msg":"error!123",
			})
		}else {
			c.JSON(200,gin.H{
				"msg":"success!",
				"data":g,
			})
		}
	})
	r.POST("/cloud_query", func(c *gin.Context) { //在上面的结构体里面要记得绑定:
		//绑定成为: Name string `json:"name" uri:"name" form:"name"`
		var g posttest
		err:=c.ShouldBindQuery(&g)
		if err!=nil{
			c.JSON(200,gin.H{
				"msg":"error!123",
			})
		}else {
			c.JSON(200,gin.H{
				"msg":"success!",
				"data":g,
			})
		}
	})
	r.Run(":9000")

}

                                                                        file传输

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main() {
	r:=gin.Default()
	r.POST("/post", func(c *gin.Context) {
		file,_ := c.FormFile("file")
		c.SaveUploadedFile(file,"./"+file.Filename)
		/*fig:=c.PostForm("fig") //多文件传输:
		name:=c.PostForm("name")*/
		c.Writer.Header().Add("Content-Disposition",fmt.Sprintf("attachment; filename=%s",file.Filename))
		c.File("./"+file.Filename)
		/*c.JSON(200,gin.H{
			"msg":file,
			"name":name,
			"fig":fig,
		})*/
	})
	r.POST("/POST_many_stdout", func(c *gin.Context) {
		form,_ := c.MultipartForm()
		file:=form.File["file"]
		fmt.Println(file)  //------流式输出 [0xc00004e230 0xc00004e280]

		for _,f :=range file{
			log.Println(f.Filename)
			//-------详细输出文件格式 如:
			//2021/08/16 16:37:55 要求.png
			//2021/08/16 16:37:55 新建文本文档.txt
		}
	})
	r.Run(":9000")

}

                                                                         gorm与db

package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type dbtype struct{
	gorm.Model
	Name string
	Age int
	Sex bool
}

func main() {
//-------------------------------------------------------------------------------------创建
	db,err:=gorm.Open("mysql","user:password@/dbname?charset=utf8mb4&parseTime=True&loc=Local")
	if err!=nil{
		fmt.Println("no!!!!!!!")
		panic(err)
	}
	db.AutoMigrate(&dbtype{})

	db.Create(&dbtype{ //完成数据库创建数据
		Name:"CloudyTenderness",
		Age: 18,
		Sex: true,
	})
//-------------------------------------------------------------------------------------查找
	var dbfir dbtype //先创建一个数据库的单件格式实例
	db.First(&dbfir)//查找函数:直接将查找的东西赋给dbfind
	fmt.Println(dbfir)//打印一下就可以看到查询的信息了

	//也可以进行信息筛选的查找
	db.First(&dbfir,"name=?","ClodyTenderness")//筛选查找,查出name=ClodyTenderness的

	//同时可以支持切片查找(找多个)
	var dbfind []dbtype //定义一个切片
	//1
	db.Find(&dbfind) // 所有的都查找出来
	//2
	db.Find(&dbfind,"age < ?",20)//所有age小于20的都会查找出来

	//规范的企业语句:3 == 2
	db.Where("age

你可能感兴趣的:(MINI压测-尝试)