Gin简介

        

Golang Gin 是一个用 Go 语言编写的 web 框架,它提供了简单而强大的 API 来构建 web 应用和服务。Gin 框架基于 net/http 包,因此它兼容标准库,并且拥有更高的性能和更多的功能。

以下是 Gin 框架的一些关键特性和优势:

  1. 快速和高效:Gin 的路由非常快,基于 radix tree 实现,使得它在处理大量请求时性能出色。

  2. 简洁的 API:Gin 提供了简洁而强大的 API,使得开发者能够快速构建 web 应用。

  3. 中间件支持:Gin 支持中间件模式,使得开发者可以方便地对请求进行预处理和后处理。

  4. 路由组:支持路由分组,可以方便地管理具有相似前缀的路由。

  5. JSON 处理:Gin 内置了 JSON 序列化和反序列化功能,可以方便地与 JSON 数据交互。

  6. 模板渲染:支持多种模板引擎,如 HTML、JSONP、XML 等。

  7. 易于测试:Gin 的设计考虑了测试性,使得编写单元测试变得简单

 

 Gin下载命令

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

 

MongoDB

        MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

MongoDB  Go driver

go get go.mongodb.org/mongo-driver/mongo

 

导入包

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"net/http"
	"time"
)

连接数据库

// 创建一个集合
var collection *mongo.Collection

// 连接数据库
func connectToMongo() (*mongo.Client, error) {
	// 创建一个上下文对象
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 创建一个MongoDB的客户端
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		fmt.Println("Failed to connect to MongoDB:", err)
	}

	// 检查连接是否成功
	err = client.Ping(ctx, nil)
	if err != nil {
		fmt.Println("Failed to ping MongoDB:", err)
	}

	//返回client
	return client, nil
}

// 初始化数据库
func initDatabase() {
	//接收client
	client, err := connectToMongo()
	if err != nil {
		log.Fatal(err)
	}

	//选择数据库并创建集合
	collection = client.Database("mydb").Collection("persons")
}

处理请求

// getinfo API
func getinfo(c *gin.Context) {
	//定义一个切片
	var items []bson.M

	//使用collection.Find查询所有数据
	cursor, err := collection.Find(context.Background(), bson.D{})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	//稍后关闭
	defer cursor.Close(context.Background())
	for cursor.Next(context.Background()) {
		var item bson.M
		err := cursor.Decode(&item)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		items = append(items, item)
	}
	if err := cursor.Err(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, items)
}

func main() {
    //调用数据库初始化函数
	initDatabase()
	//创建服务
	server := gin.Default()

	//跨域
	//使用Use方法注册中间件
	server.Use(func(c *gin.Context) {
		//允许所有源(*)
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		//允许GET, POST, OPTIONS, PUT, PATCH, DELETE请求
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		//请求方法为OPTIONS时直接返回204,没有返回内容
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		//继续
		c.Next()
	})

	//处理请求
	server.GET("/getinfo", getinfo)

	//服务器端口 默认8080
	server.Run(":5000")

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐