Go语言 gin框架 狂神

package main

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

//自定义拦截器 中间件
func myHandler() (gin.HandlerFunc) {
	return func(ctx *gin.Context) {
		ctx.Set("usersession","userid-1")
		//if {
		//
		//}
		ctx.Next()	//放行
		ctx.Abort() //阻断
	}
}


func main()  {
	//
	server := gin.Default()
	server.Use(favicon.New("./thefan.png"))
	server.GET("/hello", func(ctx *gin.Context) {
		ctx.JSON(200,gin.H{
			"code":200,
		})
	})
	//加载静态文件
	server.LoadHTMLGlob("templates/*")
	//加载资源文件
	server.Static("/static","./static")

	server.GET("/index", func(ctx *gin.Context) {
		//ctx.JSON() 返回json数据
		ctx.HTML(http.StatusOK,"index.html",gin.H{
			"msg":"后台数据",
		})
	})

	//接收前端传过来的参数
	//url/userid=xxx&username=xx
	//http://localhost:8080/user/info?userid=123&username=lf
	//server.GET("/user/info", func(ctx *gin.Context) {
	//	userId := ctx.Query("userid")
	//	userName := ctx.Query("username")
	//	ctx.JSON(200,gin.H{
	//		"code":200,
	//		"userId":userId,
	//		"userName":userName,
	//	})
	//})

	//restful
	//user/info/1/lf
	//http://localhost:8080/user/info/1/2
	server.GET("/user/info/:userid/:username",myHandler(), func(ctx *gin.Context) {
		//获取中间件的值
		usersession := ctx.MustGet("usersession").(string)
		log.Println("===========",usersession)

		userId := ctx.Param("userid")
		userName := ctx.Param("username")
		ctx.JSON(200,gin.H{
			"code":200,
			"userId":userId,
			"userName":userName,
		})
	})

	//前端给后端传递json
	server.POST("/json", func(ctx *gin.Context) {
		//request.body
		//[]byte
		b,err := ctx.GetRawData()
		if err != nil{
			return
		}
		var m map[string]interface{}
		//包装为json数据 []byte -->json
		_ = json.Unmarshal(b,&m)
		ctx.JSON(http.StatusOK,m)

	})

	server.POST("/user/add", func(ctx *gin.Context) {
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")
		if username == "lf"{
			return
		}
		ctx.JSON(200,gin.H{
			"username": username,
			"password":password,
		})
	})
	//路由
	server.GET("/test", func(ctx *gin.Context) {
		//重定向
		ctx.Redirect(http.StatusMovedPermanently,"https://www.baidu.com")
	})

	//404
	server.NoRoute(func(ctx *gin.Context) {
		ctx.HTML(http.StatusNotFound,"404.html",nil)
	})

	//路由组 /user/add
	userGroup := server.Group("/user")
	{
		userGroup.GET("/add")  //user/add
		userGroup.GET("/login")  //user/add
		userGroup.GET("/logout")  //user/add
	}
	server.Run(":8080")
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值