1.1. 介绍
-
Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确,具有快速灵活,容错方便等特点
-
对于golang而言,web框架的依赖要远比Python,Java之类的要小。自身的
net/http足够简单,性能也非常不错 -
借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范
1.2. 安装
要安装Gin软件包,您需要安装Go并首先设置Go工作区。
1.首先需要安装Go(需要1.10+版本
),然后可以使用下面的Go命令安装Gin。
go get -u github.com/gin-gonic/gin
2.将其导入您的代码中:
import "github.com/gin-gonic/gin"
3.(可选)导入net/http。例如,如果使用常量,则需要这样做http.StatusOK。
import "net/http"
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 1.创建路由
r := gin.Default()
// 2.绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
// 3.监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run("127.0.0.1:8080")
}
1)API参数:
package main
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
//截取/
action = strings.Trim(action, "/")
c.String(http.StatusOK, name+" is "+action)
})
//默认为监听8080端口
r.Run(":8000")
}
2)URL参数
- URL参数可以通过DefaultQuery()或Query()方法获取
- DefaultQuery()若参数不村则,返回默认值,Query()若不存在,返回空串
- API ? name=zs
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/user", func(c *gin.Context) {
//指定默认值
//http://localhost:8080/user 才会打印出来默认的值
name := c.DefaultQuery("name", "枯藤")
c.String(http.StatusOK, fmt.Sprintf("hello %s", name))
})
r.Run()
}
3)表单参数
- 表单传输为post请求,http常见的传输格式为四种:
- application/json
- application/x-www-form-urlencoded
- application/xml
- multipart/form-data
- 表单参数可以通过PostForm()方法获取,该方法默认解析的是x-www-form-urlencoded或from-data格式的参数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="http://localhost:8080/form" method="post" action="application/x-www-form-urlencoded"> 用户名:<input type="text" name="username" placeholder="请输入你的用户名"> <br> 密 码:<input type="password" name="userpassword" placeholder="请输入你的密码"> <br> <input type="submit" value="提交"> </form> </body> </html>package main // import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.POST("/form", func(c *gin.Context) { types := c.DefaultPostForm("type", "post") username := c.PostForm("username") password := c.PostForm("userpassword") // c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types)) c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types)) }) r.Run() }API参数: query URL参数 DefaultQuery Query 表单参数 DefaultPostForm PostForm
Gin框架入门指南:快速搭建Go Web应用
6万+

被折叠的 条评论
为什么被折叠?



