Gin框架
Gin框架 基本路由
## 路由概述 路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。 RESTful API 是目前比较成熟的一套互联网应用程序的 API 设计理论,所以我们设计我们的路由的时候建议参考 RESTful API 指南。 在 RESTful 架构中,每个网址代表一种资源,不同的请求方式表示执行不同的操作: | | | | ------------ | ------------ | | GET(SELECT) |从服务器取出资源(一项或多项) | | POST(CREATE) | 在服务器新建一个资源 | | PUT(UPDATE) | 在服务器更新资源(客户端提供改变后的完整资源) | | DELETE(DELETE)|从服务器删除资 | ## 简单的路由配置 ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) // Article :结构体的 名称与参数的 第一个字母必须大写, type Article struct { Title string Author string Desc string Content string } func main() { // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() // 绑定路由规则,执行的函数 // gin.Context,封装了request和response r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "值:%v", "这是首页index") }) router.GET("/get", getting) router.POST("/post", posting) router.PUT("/put", putting) router.DELETE("/delete", deleting) router.PATCH("/patch", patching) router.HEAD("/head", head) router.OPTIONS("/options", options) //json数据 r.GET("json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "code": 200, "msg": "json-success", }) }) //结构体 r.GET("article", func(c *gin.Context) { a := &Article{ Title: "我的祖国", Author: "ZhuYiBo", Desc: "xxxxxxxxxxxxxxxxxxxxxxxxx", Content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", } c.JSON(http.StatusOK, a) }) //响应jsonp数据 jsonp主要用来解决跨域问题。在url结尾加上callback=xxxx,将在屏幕打印xxx r.GET("jsonp", func(c *gin.Context) { a := &Article{ Title: "我的祖国", Author: "ZhuYiBo", Desc: "xxxxxxxxxxxxxxxxxxxxxxxxx", Content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", } c.JSONP(http.StatusOK, a) }) //xml r.GET("xml", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{ "code": 200, "msg": "xml-success", }) }) //html,渲染模板 router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "default/index.html", map[string]interface{}{ "title": "前台首页" }) }) // 监听端口,默认在8080 // Run("里面不指定端口号默认为8080") router.Run(":8088") } func getting(c *gin.Context) { c.String(http.StatusOK, "HTTP GET Method") } func posting(c *gin.Context) { c.String(http.StatusOK, "HTTP POST Method") } func putting(c *gin.Context) { c.String(http.StatusOK, "HTTP PUT Method") } func deleting(c *gin.Context) { c.String(http.StatusOK, "HTTP DELETE Method") } func patching(c *gin.Context) { c.String(http.StatusOK, "HTTP PATCH Method") } func head(c *gin.Context) { c.String(http.StatusOK, "HTTP HEAD Method") } func options(c *gin.Context) { c.String(http.StatusOK, "HTTP OPTIONS Method") } ``` ##http.ListenAndServe() 除了默认服务器中router.Run()的方式外,还可以用http.ListenAndServe(),比如 ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ```
顶部
收展
底部
[TOC]
目录
Gin框架 安装
Gin框架 基本路由
Gin框架 路由传值与或参数
Gin框架 路由分组和抽离
Gin框架 自定义控制器
Gin框架 中间件
Gin框架 模板
相关推荐
Go标准库