Gin框架初识

一.安装 

使用go下载gin库,命令行输入:go get github.com/gin-gonic/gin ,一般使用需要的依赖:

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

二:基本应用

1. GET 
1)gin.Context中的Query方法:get的URL传参

二:基本应用

1. GET 
1)gin.Context中的Query方法:get的URL传参

package main

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

func getQuery(context *gin.Context){

	userid := context.Query("userid")
	username := context.Query("username")

	context.String(http.StatusOK,userid+" "+username)
}
func main(){
	// 注册一个默认路由器
	router := gin.Default()

	//注册GET处理
	router.GET("/user", getQuery)

	//默认8080端口
	router.Run(":8088")
}

测试:URL:http://localhost:8088/user?userid=5&username=xiaoming 
浏览器输出:5 xiaoming

2.gin.Context中的Param方法:RESRful风格URL传参

package main

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

func getParam(context *gin.Context){

	userid := context.Param("userid")
	username := context.Param("username")

	context.String(http.StatusOK,userid+" "+username)
}
func main(){
	// 注册一个默认路由器
	router := gin.Default()

	//注册GET处理
	//router.GET("/user", getQuery)
	router.GET("/user/:userid/:username",getParam)
	//默认8080端口
	router.Run(":8088")
}

补充:/:varname必须匹配对应的,/*varname匹配后面的所有,同时不能用多个,否则编译报错 
测试:URL:http://localhost:8088/user/5/xiaoming 
页面输出:5 xiaoming