一小时快速上手GoWeb开发之Gin框架

Go是一门正在快速增长的编程语言,专为构建简单、快速且可靠的软件而设计。golang提供的net/http库已经很好了,对于http的协议的实现非常好,基于此再造框架,也不会是难事,因此生态中出现了很多框架。

Gin:Go 语言编写的Web框架,以更好的性能实现类似 Martini框架的API。

Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确。具有快速灵活,容错方便等特点。

Beego:开源的高性能Go语言Web框架。

beego是一个快速开发Go应用的http框架,go语言方面技术大牛。beego可以用来快速开发APl、Web、后端服务等各种应用,是一个RESTFul的框架,主要设计灵感来源于tornado、sinatra、flask这三个框架,但是结合了Go本身的一些特性(interface、struct继承等)而设计的一个框架。

Iris:全宇宙最快的Go语言Web框架。完备MVC支持,未来尽在掌握。

Iris是一个快速,简单但功能齐全的和非常有效的web框架。提供了一个优美的表现力和容易使用你的下一个网站或API的基础。

Gin安装使用 go get


go所有的安装都是使用go get,它的本质是git-clone 克隆,其实就是将远程仓库克隆到本地就可以使用了。

Gin是一个golang的微框架,封装比较优雅,API友好,源代码比较明确。具有快速灵活,容错方便等特点。其实对于golang而言,web框架的依赖远比Python,Java之类的要小。

自身的net/http足够简单,性能也非常不错。框架更像是一个常用函数或者工具的集合。

借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。

Gin官方文档地址:https://gin-gonic.com/zh-cn/docs/

安装gin    go get -u github.com/gin-gonic/gin

开发一个网站需要什么东西?

第一个是访问地址,其次是服务器的端口,这样就可以处理我们的请求 request response,通过这两个对象来处理请求,然后给浏览器响应一些数据。

	//创建一个服务
	ginServer := gin.Default()


    //添加连接数据库的代码,就可以直接去调用数据库,然后再写逻辑就可以返回给前端

	//处理请求的代码
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "hello world"})
	})

	//服务器端口
	ginServer.Run(":8080")

可以看到响应了msg数据json格式。

下面是添加icon,记得换浏览器,避免缓存带来的影响。

	//创建一个服务
	ginServer := gin.Default()
	//添加icon
	ginServer.Use(favicon.New("./fav.jpg"))
	//处理请求的代码
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "hello world"})
	})

	//服务器端口
	ginServer.Run(":8080")

RESTful API


以前写网站 

get  /user

post  /create_user

post  /update_user

其实也就是根据不同的请求来执行不同的功能, 以前是通过url和请求来隔离。

RESTful API  最常用

get    /user

post  /user

put   /user

delete /user

同一个路径用不同的方式。

gin框架也是支持restful api的开发。所以使用go语言去开发restful api是非常简单的。

	ginServer.POST("/user")
	ginServer.PUT("/user")
	ginServer.DELETE("/user")

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/thinkerou/favicon"
)

func main() {
	fmt.Println(gin.Version)
	//创建一个服务
	ginServer := gin.Default()
	//添加icon
	ginServer.Use(favicon.New("./fav.jpg"))
	//处理请求的代码
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": " get hello world"})
	})

	ginServer.POST("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "post hello world"})
	})

	ginServer.PUT("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "put hello world"})
	})

	//服务器端口
	ginServer.Run(":8080")

}

猜你喜欢

转载自blog.csdn.net/qq_34556414/article/details/129398086