Gin框架介绍

1. 简介Gin框架介绍
A. 基于httprouter开发的web框架。http://github.com/julienschmidt/httprouter
B. 提供Martini风格的API,但比Martini要快40倍
C. 非常轻量级,使用起来非常简洁

Gin框架介绍

2. Gin框架安装与使用
Gin框架介绍
A. 安装: go get -u github.com/gin-gonic/gin
B. import “go get -u github.com/gin-gonic/gin”

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

3. Gin框架安装与使用 Gin框架介绍

  A. 支持restful风格的API

  

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.POST("/ping", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

4. Restful风格的API
Gin框架介绍
A. 把我们设计的API抽象成一个个资源,用URI来标识。
B. 针对每一个资源,使用统一的方法进行操作。
C. 同一的方法有:
a. GET,获取资源内容。
b. POST,创建资源。
c. PUT,更新资源。
d. DELETE,删除资源。

5. 举例:用户信息接口设计,资源就是 /user/info

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/user/info", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.POST("/user/info", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.PUT("/user/info", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.DELETE("/user/info", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

6. 举例:用户信息接口设计,非restful风格的API

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/user/info", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.POST("/user/create", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.POST("/user/delete", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.POST("/user/update", func(c *gin.Context) {
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

Gin框架参数传递

1. 通过querystring传递, 比如: /user/search?username=少林&address=北京

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/user/search", func(c *gin.Context) {
//username := c.DefaultQuery("username", "少林")
username = c.Query("username")
address := c.Query("address")
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
"username": username,
"address": address,
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

2. 通过路径传递, 比如: /user/search/少林/北京

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/user/info", func(c *gin.Context) {
//username := c.DefaultQuery("username", "少林")
username = c.Query("username")
address := c.Query("address")
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
"username": username,
"address": address,
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

3. 通过表单进行提交, 比如: POST /user/search/

  A. 下载postman测试工具,测试api非常方便,下载地址: https://www.getpostman.com/apps

package main
import "github.com/gin-gonic/gin"
func main() {
//Default返回一个默认的路由引擎
r := gin.Default()
r.GET("/user/info", func(c *gin.Context) {
//username := c.DefaultQuery("username", "少林")
username = c.Query("username")
address := c.Query("address")
//输出json结果给调用方
c.JSON(, gin.H{
"message": "pong",
"username": username,
"address": address,
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}

Gin框架处理文件上传

1. 单个文件上传

package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Set a lower memory limit for multipart forms (default is 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// single file
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s", file.Filename)
// Upload the file to specific dst.
c.SaveUploadedFile(file, dst)
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("'%s' uploaded!", file.Filename),
})
})
router.Run(":8080")
}

Gin框架处理文件上传

2. 多个文件上传

package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Set a lower memory limit for multipart forms (default is 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// Multipart form
form, _ := c.MultipartForm()
files := form.File["file"]
for index, file := range files {
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("%d files uploaded!", len(files)),
})
})
router.Run(":8080")
}

Gin框架路由分组

1. 路由分组功能介绍

package main
import "github.com/gin-gonic/gin"
func login(ctx *gin.Context) {
ctx.JSON(, gin.H{
"message": "success",
})
}
func submit(ctx *gin.Context) {
ctx.JSON(, gin.H{
"message": "success",
})
}
func main() {
//Default返回一个默认的路由引擎
router := gin.Default()
// Simple group: v1
v1 := router.Group("/v1")
{
v1.POST("/login", login)
v1.POST("/submit", submit)
}
// Simple group: v2
v2 := router.Group("/v2")
{
v2.POST("/login", login)
v2.POST("/submit", submit)
}
router.Run(":8080")
}

Gin框架参数绑定

1. 为什么要参数绑定,本质上是方便,提高开发效率
Gin框架参数绑定
A. 通过反射的机制,自动提取querystring、form表单、json、xml等参数到struct中
B. 通过http协议中的context type,识别是json、xml或者表单

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Binding from JSON
type Login struct {
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// Example for binding JSON ({"user": "manu", "password": "123"})
router.POST("/loginJSON", func(c *gin.Context) {
var login Login
if err := c.ShouldBindJSON(&login); err == nil {
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// Example for binding a HTML form (user=manu&password=123)
router.POST("/loginForm", func(c *gin.Context) {
var login Login
// This will infer what binder to use depending on the content-type header.
if err := c.ShouldBind(&login); err == nil {
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// Example for binding a HTML querystring (user=manu&password=123)
router.GET("/loginForm", func(c *gin.Context) {
var login Login
if err := c.ShouldBind(&login); err == nil {
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
router.Run(":8080")
}

Gin框架渲染

1. 渲染json Gin框架渲染

A. gin.Context.JSON方法进行渲染

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// gin.H is a shortcut for map[string]interface{}
r.GET("/someJSON", func(c *gin.Context) {
//第一种方式,自己拼json
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/moreJSON", func(c *gin.Context) {
// You also can use a struct
var msg struct {
Name string `json:"user"`
Message string
Number int
}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number =
// Note that msg.Name becomes "user" in the JSON
c.JSON(http.StatusOK, msg)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}

Gin框架渲染

A. gin.Context.XML方法进行渲染

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/moreXML", func(c *gin.Context) {
// You also can use a struct
type MessageRecord struct {
Name string
Message string
Number int
}
var msg MessageRecord
msg.Name = "Lena"
msg.Message = "hey"
msg.Number =
c.XML(http.StatusOK, msg)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}

3. 渲染模板
Gin框架渲染
A. gin.Context.HTML方法进行渲染

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
})
router.GET("/users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
router.Run(":8080")
}

gin入门-1的更多相关文章

  1. gin入门

    Download and install it: $ go get github.com/gin-gonic/gin Import it in your code: import "gith ...

  2. Gin + Vue全栈开发实战(一)

    Gin入门 本章概要 Gin简介 开发第一个Gin程序 1.1 Gin简介 Gin是用Go语言编写的一个轻量级Web应用框架,现在在各个公司包括字节跳动.bilibili等大互联网公司都得到了广泛的应 ...

  3. Golang Gin实践 番外 请入门 Makefile

    Golang Gin实践 番外 请入门 Makefile 原文地址:Golang Gin实践 番外 请入门 Makefile 前言 含一定复杂度的软件工程,基本上都是先编译 A,再依赖 B,再编译 C ...

  4. Go最火的Gin框架简单入门

    Gin 介绍 Gin 是一个 Golang 写的 web 框架,具有高性能的优点,,基于 httprouter,它提供了类似martini但更好性能(路由性能约快40倍)的API服务.官方地址:htt ...

  5. GO语言GIN框架入门

    Gin框架介绍 Gin是一个用Go语言编写的web框架.它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter,速度提高了近40倍. 中文文档 Gin框架安装与使用 ...

  6. 【Go语言系列】第三方框架和库——GIN:快速入门

    要求要安装Gin软件包,需要:1.安装Go(需要1.11+版本)2.设置Go工作区 安装1.下载并安装 gin: $ go get -u github.com/gin-gonic/gin 2.将 gi ...

  7. 01 . Go框架之Gin框架从入门到熟悉(路由和上传文件)

    Gin框架简介 Gin是使用Go/Golang语言实现的HTTP Web框架, 接口简洁, 性能极高,截止1.4.0版本,包含测试代码,仅14K, 其中测试代码9K, 也就是说测试源码仅5k左右, 具 ...

  8. 02 . Go框架之Gin框架从入门到熟悉(数据解析和绑定,渲染,重定向,同步异步,中间件)

    数据解析和绑定 json数据解析和绑定 package main import ( "github.com/gin-gonic/gin" "net/http" ...

  9. 03 . Go框架之Gin框架从入门到熟悉(Cookie和Session,数据库操作)

    Cookie Cookie是什么 HTTP是无状态协议,服务器不能记录浏览器的访问状态,也就是说服务器不能区分两次请求是否由同一个客户端发出 Cookie就是解决HTTP协议无状态的方案之一,中文是小 ...

随机推荐

  1. 实现Linux下不间断聊天和退出处理

    实现Linux下不间断聊天和退出处理

  2. 0908NOIP模拟测试赛后总结

    %%%skyh rank1- 奶风神.kx.有钱人 rank2-210 NC锅.RNB.B哥 rank5-200 我 rank32- 9-13upd:无意中点进了某个博客发现我竟然考场上yy出了树上莫 ...

  3. Vue Element 使用 icon 图标 (第三方)

    Vue Element 使用 icon 图标 (第三方) element-ui 自带的图标库还是不够全, 还是需要需要引入第三方 icon, 自己在用的时候一直有些问题, 参考了些教程, 详细地记录补 ...

  4. python 中动态类的创建

    参考 collections.namedtuple 的实现 链接: https://www.cnblogs.com/BeautifulWorld/p/11647198.html

  5. linux 备份最近一天的文件

    #!/bin/bash #备份在最近一天修改的文件 #date 获取日期 +%Y-%m-%d 设置日期格式为yyyy-mm-dd的形式 BACKFILE=backup-$(date +%Y-%m-%d ...

  6. Error: Could not link: /usr/local/share/doc/homebrew

    mac 执行brew update 报错 Error: Could not link: /usr/local/share/doc/homebrew 更新brew,报错 Error: Could not ...

  7. js 倒计时毫秒级别显示

    <html> <head> <style> div{ width:100%; text-align:center; font-size: 14px; } </ ...

  8. ES6之主要知识点(六)数组

    引自http://es6.ruanyifeng.com/#docs/array 1.扩展运算符(...) 扩展运算符(spread)是三个点(...).它好比 rest 参数的逆运算,将一个数组转为用 ...

  9. MFC安装与部署(程序打包)

    (发现csdn传照片实在是太麻烦, 不能够直接拖拽进来;所以我直接使用云笔记生成一张图片 直接完成!) (懒癌晚期-)

  10. OSG实现正八面体剖分成球

    #include<Windows.h> #include<osg/Node> #include<osg/Geode> #include<osg/Group&g ...