Gin框架来实现HTTP请求和参数解析

1.方式一:RouterMain

package main

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

func  main(){
	engine:=gin.Default()
	//http://localhost:8080/hello?name=davie
	engine.GET("/hello", func(context *gin.Context) {
		fmt.Println(context.FullPath())
		name:=context.Query("name")
		fmt.Println(name)

		context.Writer.Write([]byte("hello,"+name))

	})


	//http://localhost:8080/login
	/*
	在Postman软件中,设置访问方式为POST,网址为http://localhost:8080/login;在Body中选择x-www-form-urlencoded
	并填入:
	key:username  value:davie
	key:password  value:123
	 */
	engine.POST("/login", func(context *gin.Context) {
		fmt.Println(context.FullPath())
		username,exist:=context.GetPostForm("username")
		if exist{
			fmt.Println(username)
		}

		password,exist:=context.GetPostForm("password")
		if exist{
			fmt.Println(password)
		}

		context.Writer.Write([]byte(username+"登录"))
	})

	//删除的是某个用户的值,:id代表的是变量
	engine.DELETE("/user/:id", func(context *gin.Context) {
		userID:=context.Param("id")
		fmt.Println(userID)
		context.Writer.Write([]byte("delete 用户ID:"+userID))
	})

	engine.Run()
}

2.方式二:HandleMain

package main

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

func main(){
	engine:=gin.Default()
	//http://localhost:8080/hello?name=davie
	engine.Handle("GET","/hello", func(context *gin.Context) {
		path:=context.FullPath()
		fmt.Println(path)//终端输出

		name:=context.DefaultQuery("name","hello")
		fmt.Println(name)//终端输出

		//浏览器界面请求的输出
		context.Writer.Write([]byte("hello,"+name))
	})

	//post
	//http://localhost: 8080/login
	engine.Handle("POST","/login", func(context *gin.Context) {
		fmt.Println(context.FullPath())
		username := context.PostForm("username")
		password :=context.PostForm("password")
		fmt.Println(username)//终端输出
		fmt.Println(password)//终端输出

		//浏览器界面请求的输出
		context.Writer.Write([]byte(username+"登录"))
	})
	engine.Run()
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值