gin快速入门

举报
Nick Qiu 发表于 2021/07/31 17:07:09 2021/07/31
【摘要】 简介gin是go语言的web框架,其API与martini类似,性能是httprouter的40倍,如果我们需要一个高性能的web服务器,gin是一个很好的选择 安装gin安装# go语言版本需要高于1.13go get -u github.com/gin-gonic/gin在代码内倒入ginimport "github.com/gin-gonic/gin"如果使用了变量http.Stat...

简介

gin是go语言的web框架,其API与martini类似,性能是httprouter的40倍,如果我们需要一个高性能的web服务器,gin是一个很好的选择

安装gin

  • 安装
# go语言版本需要高于1.13
go get -u github.com/gin-gonic/gin
  • 在代码内倒入gin
import "github.com/gin-gonic/gin"
  • 如果使用了变量http.StatusOK,则需要导入net/http
import "net/http"

快速开始

  • 新建文件
mkdir main
touch main/example.go
  • example.go
package main

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

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
  • 执行程序
go run  main/example.go
# 新开一个窗口输入如下命令,会应答 字符串 {"message":"pong"}
curl localhost:8080/ping

API例子

可在官方网站上找到很多可执行的gin例

  • 使用GET, POST, PUT, PATCH, DELETE和OPTIONS
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	// Creates a gin router with default middleware:
	// logger and recovery (crash-free) middleware
	router := gin.Default()

	router.GET("/someGet", getting)
	router.POST("/somePost", posting)
	router.PUT("/somePut", putting)
	router.DELETE("/someDelete", deleting)
	router.PATCH("/somePatch", patching)
	router.HEAD("/someHead", head)
	router.OPTIONS("/someOptions", options)

	// By default it serves on :8080 unless a
	// PORT environment variable was defined.
	router.Run()
	// router.Run(":3000") for a hard coded port
}

// curl localhost:8080/someGet
func getting(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "GET")
}

// curl -X POST localhost:8080/somePost
func posting(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "POST")
}
func putting(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "PUT")
}

func deleting(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "DELETE")
}
func patching(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "PATCH")
}
func head(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "HEAD")
}
func options(c *gin.Context) {
	c.String(http.StatusOK, "Hello %s", "OPTIONS")
}

  • url含参数
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	// This handler will match /user/john but will not match /user/ or /user
	// curl localhost:8080/user/nick
	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// However, this one will match /user/john/ and also /user/john/send
	// If no other routers match /user/john, it will redirect to /user/john/
	// curl localhost:8080/user/nick/fly
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})


	router.Run(":8080")
}

  • post简单参数
package main

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

func main() {
	router := gin.Default()
	// curl -X POST -H "Content-Type: Multipart/Urlencoded" localhost:8080/form_post -d "message=hello&nick=dddd"
	router.POST("/form_post", func(c *gin.Context) {
		message := c.PostForm("message")
		nick := c.DefaultPostForm("nick", "anonymous")

		c.JSON(200, gin.H{
			"status":  "posted",
			"message": message,
			"nick":    nick,
		})
	})
	router.Run(":8080")
}

  • 从url和data一同获取参数
package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

func main() {

	router := gin.Default()
	// curl -X POST -H "Content-Type: application/x-www-form-urlencoded" "localhost:8080/post?id=123&page=12" -d "name=manu&message=this_is_great"
	router.POST("/post", func(c *gin.Context) {
		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")
		fmt.Printf("\n This fo test.  id: %s; page: %s; name: %s; message: %s\n", id, page, name, message)
	})
	router.Run(":8080")
}

  • 上传单个文件
package main

import (
	"fmt"
	"net/http"
	"path/filepath"

	"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.Static("/", "./public")
	router.POST("/upload", func(c *gin.Context) {
		name := c.PostForm("name")
		email := c.PostForm("email")

		// Source
		file, err := c.FormFile("file")
		if err != nil {
			c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
			return
		}

		filename := filepath.Base(file.Filename)
		fmt.Println("filename=" + filename)
		if err := c.SaveUploadedFile(file, "public/"+filename); err != nil {
			c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
			return
		}

		c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email))
	})
	router.Run(":8080")
}

curl -X POST http://localhost:8080/upload -F "file=@./temp.md;filename=temp.md" -F "name=nick.md" -F "email=mail111" -H "Content-Type: multipart/form-data",输入命令可以上传本地文件./temp.md
curl http://localhost:8080/temp.md,输入命令可以访问刚刚上传的文件

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。