gin c.html(),go web框架gin介绍和使用(一)

本文是关于Go语言web框架Gin的入门介绍,内容涵盖Gin的性能优势、安装、基本使用、常见请求方法、路由参数、查询参数、POST请求参数、文件上传(单文件和多文件)以及如何结合HTML模板实现表单上传。通过实例代码,详细解析了Gin的使用流程和关键功能。
摘要由CSDN通过智能技术生成

本文是gin介绍和使用的第一篇文章。

一、简要介绍

Gin的官方说明如下:

Gin is a web framework written in Go (Golang). It features a martini-like API with much better

performance, up to 40 times faster thanks to httprouter. If you need performance and good

productivity, you will love Gin.

简单来说,Gin是一个Go的微框架,基于 httprouter,提供了类似martini(也是一个go web框架)但更好性能的API服务。

Gin具有运行速度快、良好的分组路由、合理的异常捕获和错误处理、优良的中间件支持和 json处理支持等优点,是一款非常值得推荐的web框架。

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

二、使用详解

1.安装

要安装Gin包,首先需要安装Go((Go版本1.10+)并设置Go工作区

下载并安装:

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

在代码中导入它

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

2. 简单示例:

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

}

简单几行代码,就实现了一个web服务。

首先,使用gin的Default方法创建一个路由handle;

然后,通过HTTP方法绑定路由规则和路由函数;

最后,启动路由的Run方法监听端口。

不同于net/http库的路由函数,gin进行了封装,把request和response都封装到gin.Context的上下文环境。

3. 常用请求方法

除了GET方法,gin也支持POST,PUT,DELETE,OPTION等常用的restful方法:

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

}

4. 获取路径中的参数

gin的路由来自httprouter库。因此httprouter具有的功能,gin也具有,不过gin不支持路由正则表达式:

package main

import (

"fmt"

"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

router.GET("/user/:name", func(c *gin.Context) {

name := c.Param("name")

c.String(http.StatusOK, "Hello %s", name)

})

// Howerer, this one will match /user/john/ and also /user/john/send

// if no other routers match /user/john, it will redirect to /user/john/

router.GET("/user/:name/*action", func(c *gin.Cont

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值