Go learn --Web frame assembly Gin

Before the time to learn Java, Spring and family bucket lay a good relationship on the line, from Spring, Spring MVC to SpringBoot, the same strain.

For a Web project, using Spring MVC, MVC will be based on the idea of ​​a development project, whether it is to deal with before and after the end of the separation or not separation scenes, you can easily manage. Because you just know that you're using a Web development framework on the line.

Compared to Spring Java in a dominant situation, Go Ecology Web framework is still contending stage. Starting today learning a Web-based development framework Gin Go language development.

Brief introduction

Github:https://github.com/gin-gonic/gin

Language: Go Language

Official website: https: //gin-gonic.com/

 

Environment to build

Go Version: 1.12.4

System: macOS

Dependency management tool: go mod

IDE:Goland

Because I used go mod, so references to gin dependence is considered a very convenient.

How to create a new project go mod management and how to transform old items to go mod, you can see this article: https: //juejin.im/post/5c8e503a6fb9a070d878184a, written in great detail.

This is my go-demo: https: all third-party //github.com/DMinerJackie/go-demo project relied.

So it depends how to add gin? There are three ways

  • Create a direct example of gin-based program file, and then execute or command, go mod will automatically help you download and update go.mod gin rely file.go build xxx.gogo run xxx.go

  • Above, or create a new example program file, and then execute the project root directory go mod tidycommand, go mod will help you arrange on. This command can help you remove unwanted dependencies, and pull quote rely on your need.

  • In go.mod file manually add dependency similar such.github.com/gin-gonic/gin v1.4.0

Almost anything without cumbersome steps to complete the build environment. The following began to write the first of Gin-based demo

 

First Demo

1, the new file helloworld.go

main Package 

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

FUNC main () { 
	R & lt: = gin.Default () 
	r.get ( "/ of ping", FUNC (C * gin.Context) { 
		c.JSON (200 is , gin.H { 
			"the Message": "Pong", 
		}) 
	}) 
	r.Run () // and start listening service on 0.0.0.0:8080 
}

  

2. Click the implementation of the program

As can be seen from the console program service has started, and starts listening on port 8080

3, access interface

Next we enter localhost in the browser: 8080 / ping you can see the results of the program returns

A minimalist set up a Web server so complete and Foreign visit.

The above code

By declaring a gin engine, subsequent operations are based on this engine.r:=gin.Default()

By declare a route that can be accessed, HTTP request method defined for the GET request. Also defines corresponding handling the request, i.e., a closure function declaration JSON format returned key pair.r.GET

By listening on the specified port and start the servicer.Run()

 

Other Demo

1, rendering HTML

Although many have advocated and implemented before and after the end of the separation, and that is only to provide the back-end HTTP interface, HTTP interface and is responsible for calling the front page rendering.

But there are usage scenarios before and after the end rub together, gin provides this capability.

具体的做法是提供一个HTML模板,服务端将得到的数据填充到模板中实现页面的渲染。

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

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("main/src/gin-example/examples/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")
}

  

index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

  

user.tmpl

{{ define "users/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

  

对应的HTML模板文件目录结构如下

代码部分

router.LoadHTMLGlob用于指明HTML模板文件的路径

router.GET同上,定义访问路由和返回结果,不同于第一个Demo的是,这里有赋值填充的过程,比如

c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
			"title": "Posts",
		})

  

将index.tmpl中定义的 .title替换为"Posts"

执行结果如下

2、PureJSON

func main() {
	r := gin.Default()
	
	// 提供 unicode 实体
	r.GET("/json", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"html": "<b>Hello, 世界!</b>",
		})
	})
	
	// 提供字面字符
	r.GET("/purejson", func(c *gin.Context) {
		c.PureJSON(200, gin.H{
			"html": "<b>Hello, 世界!</b>",
		})
	})
	
	// 监听并在 0.0.0.0:8080 上启动服务
	r.Run(":8080")
}

  

这里两个GET方法唯一不同的就是要渲染的内容一个使用JSON()方法一个使用PureJSON()方法。

启动程序后,我们看下访问结果有什么不同

可以看出JSON()渲染的会有中文以及标签转为unicode编码,但是使用PureJSON()渲染就是原样输出(我的浏览器装了插件,会自动解码,所以不点击右边的”RAW“两个接口返回的结果是一样的)。

这个问题,本周我们服务端在和客户端对接的时候还遇到了,因为框架返回的JSON串就是经过编码的,但是单独请求放到浏览器是没有问题的,客户端收到的却是经过编码的,最后排查发现是浏览器插件解码了。

3、渲染多种数据交换格式的数据

gin支持渲染XML、JSON、YAML和ProtoBuf等多种数据格式

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

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

	// gin.H 是 map[string]interface{} 的一种快捷方式
	r.GET("/someJSON", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/moreJSON", func(c *gin.Context) {
		// 你也可以使用一个结构体
		var msg struct {
			Name    string `json:"user"`
			Message string
			Number  int
		}
		msg.Name = "Lena"
		msg.Message = "hey"
		msg.Number = 123
		// 注意 msg.Name 在 JSON 中变成了 "user"
		// 将输出:{"user": "Lena", "Message": "hey", "Number": 123}
		c.JSON(http.StatusOK, msg)
	})

	r.GET("/someXML", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/someYAML", func(c *gin.Context) {
		c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/someProtoBuf", func(c *gin.Context) {
		reps := []int64{int64(1), int64(2)}
		label := "test"
		// protobuf 的具体定义写在 testdata/protoexample 文件中。
		data := &protoexample.Test{
			Label: &label,
			Reps:  reps,
		}
		// 请注意,数据在响应中变为二进制数据
		// 将输出被 protoexample.Test protobuf 序列化了的数据
		c.ProtoBuf(http.StatusOK, data)
	})

	// 监听并在 0.0.0.0:8080 上启动服务
	r.Run(":8080")
}

  

今天先到这,后面再看看gin的源码。

 

如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!如果您想持续关注我的文章,请扫描二维码,关注JackieZheng的微信公众号,我会将我的文章推送给您,并和您一起分享我日常阅读过的优质文章。

Guess you like

Origin www.cnblogs.com/bigdataZJ/p/gin-helloworld.html