gin-gonic Go轻量级restful服务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gin-gonic Go轻量级restful服务相关的知识,希望对你有一定的参考价值。

参考技术A https://github.com/gin-gonic

https://github.com/gin-gonic/gin#quick-start

指定port

启动完成之后,就可以使用HTTP工具进行访问,如同一个tomcat,而且比较轻量级。

客户端我就抄了一个可用的,毕竟我不会写

学习go gin框架

1、路由 - Restful风格

package main

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

func main()  
	//返回默认的路由引擎
	r := gin.Default()

	//Restful风格请求,使用postman工具请求测试
	//获取
	r.GET("/hello", func(c *gin.Context) 
		c.JSON(200,gin.H
			"message":"Hello Golang",
			"method":"GET",
		)
	)
	//创建
	r.POST("/hello", func(c *gin.Context) 
		c.JSON(http.StatusOK,gin.H
			"message":"Hello Golang",
			"method":"POST",
		)
	)
	//更新
	r.PUT("/hello", func(c *gin.Context) 
		c.JSON(http.StatusOK,gin.H
			"message":"Hello Golang",
			"method":"PUT",
		)
	)
	//删除
	r.DELETE("/hello", func(c *gin.Context) 
		c.JSON(http.StatusOK,gin.H
			"message":"Hello Golang",
			"method":"DELETE",
		)
	)

	//启动服务,默认8080端口
	r.Run()
	//自定义端口
	//r.Run(":9090")

2、路由参数

1 - 路径参数

package main

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

func main()
	r := gin.Default()
	//第一种访问:/user/:?/:?
	url := "/user/:name/:age/*action"

	r.GET(url, func(c *gin.Context) 
		name := c.Param("name")
		age := c.Param("age")
		//截取
		action := strings.Trim(c.Param("action"),"/")
		fmt.Println("action=",action)

		c.String(http.StatusOK,"姓名:" + name + ",年龄:" + age)
	)

	r.Run()


2 - query参数

package main

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

func main()
	r := gin.Default()
	//第二种访问:/user?xx=xxx
	url := "/user"

	r.GET(url, func(c *gin.Context) 
		name := c.Query("name")
		age := c.Query("age")

		c.String(http.StatusOK,"姓名:" + name + ",年龄:" + age)
	)

	r.Run()


3 - 表单参数

package main

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

func main()
	r := gin.Default()
	//表单访问:/user
	url := "/form"

	r.POST(url, func(c *gin.Context) 
		name := c.PostForm("name")
		age := c.PostForm("age")

		c.String(http.StatusOK,"姓名:" + name + ",年龄:" + age)
	)

	r.Run()


#form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/form" method="post">
  用户名:<input type="text" name="name" placeholder="请输入你的用户名" value="JackyChen"></br>
  年龄:<input type="text" name="age" placeholder="请输入你的年龄" value="18"></br>
    <button type="submit">提交</button>
</form>
</body>
</html>



4 - 默认参数

package main

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

func main()
	r := gin.Default()
	//默认参数访问:http://localhost:8080/user
	//带参数访问:http://localhost:8080/user?name=JackyChen&age=18
	url := "/user"
	r.GET(url, func(c *gin.Context) 
		name := c.DefaultQuery("name","JackyChen")
		age := c.DefaultQuery("age","25")
		c.String(http.StatusOK,"姓名:" + name + ",年龄:" + age)
	)
	
	//当表单参数不存在name,age时,使用默认参数
	url = "/form"
	r.POST(url, func(c *gin.Context) 
		name := c.DefaultPostForm("name","JackyChen")
		age := c.DefaultPostForm("age","25")
		c.String(http.StatusOK,"姓名:" + name + ",年龄:" + age)
	)

	r.Run()

3、上传文件

1 - 上传单个文件

package main

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

func main()  
	r := gin.Default()
	
	r.POST("/upload", func(c *gin.Context) 
		//获取上传文件
		//file, err := c.FormFile("file")
		_, file, err := c.Request.FormFile("file")
		if err != nil
			c.String(http.StatusOK,"上传图片错误")
		

		//获取文件大小
		fmt.Println(file.Size)
		//获取文件类型
		fmt.Println(file.Header.Get("Content-Type"))

		//保存文件到当前目录下./file.Filename(文件名)
		_ = c.SaveUploadedFile(file,file.Filename)
		c.String(http.StatusOK,file.Filename)
	)

	r.Run()


# single.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
    上传文件:<input type="file" name="file" >
    <input type="submit" value="提交">
</form>
</body>
</html>

2 - 上传多个文件

package main

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

func main()  
	r := gin.Default()
	//限制表单上传大小 8MB,默认为32MB
	r.MaxMultipartMemory = 8 << 20
	r.POST("/uploads", func(c *gin.Context) 
		//获取表单大小,限制200000
		//err := c.Request.ParseMultipartForm(200000)
		//form := c.Request.MultipartForm
		
		//获取表单
		form, err := c.MultipartForm()
		if err != nil 
			c.String(http.StatusOK,"上传图片错误")
		
		//获取所有图片数组
		files := form.File["files"]
		//循环存储
		for _, file := range files 
			if err := c.SaveUploadedFile(file,file.Filename); err != nil 
				c.String(http.StatusBadRequest,"upload err %s",err.Error())
				return
			
		
		c.String(http.StatusOK,"上传成功")
	)

	r.Run()


# multi.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/uploads" method="post" enctype="multipart/form-data">
    上传文件:<input type="file" name="files" multiple>
    <input type="submit" value="提交">
</form>
</body>
</html>

路由分组

package main

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

func main()  
	r := gin.Default()
	//默认使用了2个中间件Logger(), Recovery()
	//创建路由组
	group := r.Group("/group")
	//  是书写规范
	
		group.GET("/login",login)
		group.GET("/register",register)
	

	r.Run()


func login(c *gin.Context)  
	c.String(http.StatusOK,"login")


func register(c *gin.Context)  
	c.String(http.StatusOK,"register")

路由注册与拆分

1 - 根据功能模块拆分

# main.go

package main

import (
	"gin/5-RouteSplitRegister/routers"
	"github.com/gin-gonic/gin"
)

func main()  
	r := gin.Default()
	routers.LoadBlog(r)
	routers.LoadShop(r)
	r.Run()


# blog.go

package routers

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

func commentHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello comment",
	)


func forwardHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello forward",
	)


func LoadBlog(e *gin.Engine) 
	e.GET("/comment",commentHandler)
	e.GET("/forward",forwardHandler)


# shop.go

package routers

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

func buyHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello buy",
	)


func collectHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello collect",
	)


func LoadShop(e *gin.Engine) 
	e.GET("/buy",buyHandler)
	e.GET("/collect",collectHandler)


2 - 根据app应用拆分

# main.go

package main

import (
	"gin/5-RouteSplitRegister/app/blog"
	"gin/5-RouteSplitRegister/app/shop"
	"gin/5-RouteSplitRegister/routers"
)

func main()  
	//根据app应用拆分
	routers.Include(blog.Routers,shop.Routers)
	r := routers.Init()

	//根据功能模块拆分
	routers.LoadBlog(r)
	routers.LoadShop(r)
	r.Run()


# routers.go
package routers

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

//定义路由结构体匿名方法
type Option func(*gin.Engine)
//定义路由方法数组
var options = []Option

//注册app路由配置
func Include(opts ...Option)  
	options = append(options,opts...)


//初始化路由
func Init() *gin.Engine 
	r := gin.New()
	for _, opt := range options 
		opt(r)
	
	return  r


# blog/router.go
package blog

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

func Routers(e *gin.Engine) 
	e.GET("/star",starHandler)
	e.GET("/share",shareHandler)

# blog/hanlder.go
package blog

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

func starHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello star",
	)


func shareHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello share",
	)


# shop/router.go
package shop

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

func Routers(e *gin.Engine) 
	e.GET("/login",loginHandler)
	e.GET("/register",registerHandler)

# shop/hanlder.go
package shop

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

func loginHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello login",
	)


func registerHandler(c *gin.Context)  
	c.JSON(http.StatusOK,gin.H
		"message":"Hello register",
	)

6、参数绑定

package main

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

以上是关于gin-gonic Go轻量级restful服务的主要内容,如果未能解决你的问题,请参考以下文章

基于gin web框架搭建RESTful API服务

学习go gin框架

学习go gin框架

学习go gin框架

学习go gin框架

AgileConfig - RESTful API 介绍