Go-Gin快速入门

723 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第29天,点击查看活动详情

前言

  本教程是关于go的web开发框架的快速入门,适合新手,希望对你有帮助。

1、简介

官方介绍:

  Gin 是一个用 Go (Golang) 编写的 Web 框架。 它具有类似 martini 的 API,性能要好得多,多亏了 httprouter,速度提高了 40 倍。 如果您需要性能和良好的生产力,您一定会喜欢 Gin。

image.png

特性

  • 快速

基于 Radix 树的路由,小内存占用。没有反射。可预测的 API 性能。

  • 支持中间件

传入的 HTTP 请求可以由一系列中间件和最终操作来处理。 例如:Logger,Authorization,GZIP,最终操作 DB。

  • Crash 处理

Gin 可以 catch 一个发生在 HTTP 请求中的 panic 并 recover 它。这样,你的服务器将始终可用。例如,你可以向 Sentry 报告这个 panic!

  • JSON 验证

Gin 可以解析并验证请求的 JSON,例如检查所需值的存在。

  • 路由组

更好地组织路由。是否需要授权,不同的 API 版本…… 此外,这些组可以无限制地嵌套而不会降低性能。

  • 错误管理

Gin 提供了一种方便的方法来收集 HTTP 请求期间发生的所有错误。最终,中间件可以将它们写入日志文件,数据库并通过网络发送。

  • 内置渲染

Gin 为 JSON,XML 和 HTML 渲染提供了易于使用的 API。

  • 可扩展性

2、快速入门

1、要求

  • Go 1.13 及以上版本

2、安装

要安装 Gin 软件包,需要先安装 Go 并设置 Go 工作区。

1.下载并安装 gin:

$ go get -u github.com/gin-gonic/gin

报错信息:

go: module github.com/gin-gonic/gin: Get "https://proxy.golang.org/github.com/gin-gonic/gin/@v/list": dial tcp 172.217.163.49:443: connectex: A connection attempt failed because the conn
ected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
​

解决方案:

在终端依次输入:

go env -w GO111MODULE=on
​
go env -w GOPROXY=代理

GOPROXY,目前国内常用的go代理:

goproxy.io
https://goproxy.io,direct
​
七牛云
https://goproxy.cn
​
阿里云
https://mirrors.aliyun.com/goproxy/

2.将 gin 引入到代码中:

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

3.(可选)如果使用诸如 http.StatusOK 之类的常量,则需要引入 net/http 包:

import "net/http"
  1. 创建你的项目文件夹并 cd 进去
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
  1. 拷贝一个初始模板到你的项目里
$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
  1. 运行你的项目
$ go run main.go

3、代码:

package main
​
import (
    "github.com/gin-gonic/gin"
)
​
func main() {
    //创建服务
    ginServer := gin.Default()
    ginServer.GET("/hello", func(context *gin.Context) {
        context.JSONP(200, gin.H{"msg": "Hello"})
    })
    //服务器端口号
    ginServer.Run(":10086")
}
​

4、测试

启动项目,在浏览器测试,请求10086端口号。

image-20221027134735734.png

总结

  今天学习了go的web开发-使用了gin,算是成功启动起来了一个Hellowoeld项目,希望对你有所帮助。