Skip to content

Latest commit

 

History

History
168 lines (123 loc) · 3.72 KB

File metadata and controls

168 lines (123 loc) · 3.72 KB

第2节 gin框架

❤️💕💕Go语言的web框架gin框架、gorm基本使用以及web开发项目实战,更多请移步我的博客Myblog:http://nsddd.top


[TOC]

引入gin包

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

导入

go get github.com/gin-gonic/gin

使用gin包

/*
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-09-01 15:43:30
 * @LastEditors: xiongxinwei 3293172751nss@gmail.com
 * @LastEditTime: 2022-09-01 15:52:03
 * @FilePath: \code\markdown\gin\gin.go
 */
package main

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

func sayHello(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "hello golang",
	})

}

func main() {
	r := gin.Default() //返回默认的路由引擎

	//指定用户使用GET请求访问/hello时,执行sayHello这个函数
	r.GET("/hello", sayHello)

	//启动服务
	r.Run(":9000")
}

image-20220901155330191

我们在第一节中,是把所有的东西写到一个文件中,然后后端工程师将文件读取出来,通过http返回给浏览器.但是浏览器的信息特别多,所以在同样的带宽下面,数据越多,需要的时间越长.

所以现在是无需所有的信息,后端的服务只提供数据,不生成html代码(前后端分离),不走后端服务了.

当我们开发移动端或者app的时候,无需提供两份服务,只需要提供一份数据.

func main() {
	r := gin.Default() //返回默认的路由引擎

	//指定用户使用GET请求访问/hello时,执行sayHello这个函数
	r.GET("/hello", sayHello)

	//HTTP请求的四个不同的方法,表示四个不同的动作
	r.GET("/book", sayHello)
	r.POST("/book", sayHello)
	r.PUT("/book", sayHello)
	r.DELETE("/book", sayHello)

	//启动服务
	r.Run(":9000")
}

开发RESTful API 的时候我们通常使用Postman来作为客户端的测试工具

/*
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-09-01 15:43:30
 * @LastEditors: xiongxinwei 3293172751nss@gmail.com
 * @LastEditTime: 2022-09-01 16:29:33
 * @FilePath: \code\markdown\gin\gin.go
 * @Description:
 *
 *
 */
package main

import (
	"net/http"

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

func sayHello(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "hello golang",
	})

}

func main() {
	r := gin.Default() //返回默认的路由引擎

	//指定用户使用GET请求访问/hello时,执行sayHello这个函数
	r.GET("/hello", sayHello)

	r.GET("/book", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"method": "GET",
		})
	})
	r.POST("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{ //http.StatusOK:200
			"method": "POST",
		})
	})
	r.PUT("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{ //http.StatusOK:200
			"method": "PUT",
		})
	})
	r.DELETE("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{ //http.StatusOK:200
			"method": "DELETE",
		})
	})

	//启动服务
	r.Run(":9000")
}

我们拿到GET请求

image-20220901163239268

拿到post请求

image-20220901163320262

关于REST API看下一节⏬⏬⏬

END 链接