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()
}