搜索
首页后端开发Golang使用 Go 为 AG-Grid 创建 API

Create an API for AG-Grid with Go

AG-Grid 是一个功能强大的 JavaScript 数据网格库,非常适合构建具有排序、过滤和分页等功能的动态高性能表格。在本文中,我们将在 Go 中创建一个 API 来支持 AG-Grid,从而实现高效的服务器端数据操作,包括过滤、排序和分页。通过将 AG-Grid 与 Go API 集成,我们将开发一个强大的解决方案,即使在处理大型数据集时也能确保平稳的性能。

先决条件

  • 去1.21
  • MySQL

设置项目

设置 Go 项目依赖项。

go mod init app
go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/mysql
go get github.com/joho/godotenv

创建名为“example”的测试数据库,并运行database.sql文件导入表和数据。

项目结构

├─ .env
├─ main.go
├─ config
│  └─ db.go
├─ controllers
│  └─ product_controller.go
├─ models
│  └─ product.go
├─ public
│  └─ index.html
└─ router
   └─ router.go

项目文件

.env

此文件包含数据库连接信息。

DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=example
DB_USER=root
DB_PASSWORD=

数据库Go

此文件使用 GORM 设置数据库连接。它声明了一个全局变量 DB 来保存数据库连接实例,以便稍后在我们的应用程序中使用。

package config

import (
    "fmt"
    "os"

    "github.com/joho/godotenv"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
)

var DB *gorm.DB

func SetupDatabase() {
    godotenv.Load()
    connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_DATABASE"))
    db, _ := gorm.Open(mysql.Open(connection), &gorm.Config{NamingStrategy: schema.NamingStrategy{SingularTable: true}})
    DB = db
}

路由器.go

此文件为 Gin Web 应用程序设置路由。它初始化 DataTables API 的路由器并在根 URL 处提供静态 index.html 文件。

package router

import (
    "app/controllers"

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

func SetupRouter() {
    productController := controllers.ProductController{}
    router := gin.Default()
    router.StaticFile("/", "./public/index.html")
    router.GET("/api/products", productController.Index)
    router.Run()
}

产品.go

此文件定义应用程序的产品模型。

package models

type Product struct {
    Id int
    Name string
    Price float64
}

产品控制器.go

此文件定义了一个函数来处理传入请求并返回 DataTables 数据。

package controllers

import (
    "app/config"
    "app/models"
    "net/http"
    "strconv"

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

type ProductController struct {
}

func (con *ProductController) Index(c *gin.Context) {
    size, _ := strconv.Atoi(c.DefaultQuery("length", "10"))
    start, _ := strconv.Atoi(c.Query("start"))
    order := "id"
    if c.Query("order[0][column]") != "" {
        order = c.Query("columns[" + c.Query("order[0][column]") + "][data]")
    }
    direction := c.DefaultQuery("order[0][dir]", "asc")
    var products []models.Product
    query := config.DB.Model(&products)
    var recordsTotal, recordsFiltered int64
    query.Count(&recordsTotal)
    search := c.Query("search[value]")
    if search != "" {
        search = "%" + search + "%"
        query.Where("name like ?", search)
    }
    query.Count(&recordsFiltered)
    query.Order(order + " " + direction).
        Offset(start).
        Limit(size).
        Find(&products)
    c.JSON(http.StatusOK, gin.H{"draw": c.Query("draw"), "recordsTotal": recordsTotal, "recordsFiltered": recordsFiltered, "data": products})
}

product_controller.go 文件定义了一个控制器,用于使用 Gin 框架管理 Go 应用程序中与产品相关的 API 请求。它具有一个 Index 方法,可根据分页、排序和搜索的查询参数检索分页的产品列表。该方法提取分页参数,构造查询以从数据库中获取产品,并在提供搜索词的情况下应用过滤。在统计匹配产品总数后,它会对结果进行排序和限制,然后返回包含产品数据和总数的 JSON 响应,以便于与前端应用程序集成。

主程序

该文件是我们应用程序的主要入口点。它将创建并设置 Gin Web 应用程序。

package main

import (
    "app/config"
    "app/router"
)

func main() {
    config.SetupDatabase()
    router.SetupRouter()
}

索引.html


    <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>


    <div>



<p>The index.html file sets up a web page that uses the AG-Grid library to display a dynamic data grid for products. It includes a grid styled with the AG-Grid theme and a JavaScript section that constructs query parameters for pagination, sorting, and filtering. The grid is configured with columns for ID, Name, and Price, and it fetches product data from an API endpoint based on user interactions. Upon loading, the grid is initialized, allowing users to view and manipulate the product list effectively.</p>

<h2>
  
  
  Run project
</h2>



<pre class="brush:php;toolbar:false">go run main.go

打开网络浏览器并转到http://localhost:8080

你会发现这个测试页。

Create an API for AG-Grid with Go

测试

页面大小测试

从“页面大小”下拉列表中选择 50 来更改页面大小。每页将显示 50 条记录,最后一页将从 5 条变为 2 条。

Create an API for AG-Grid with Go

分选测试

单击第一列的标题。您将看到 id 列将按降序排序。

Create an API for AG-Grid with Go

搜索测试

在“名称”栏的搜索文本框中输入“否”,您将看到过滤后的结果数据。

Create an API for AG-Grid with Go

结论

总之,我们有效地将 AG-Grid 与 Go API 集成,以创建强大且高效的数据网格解决方案。通过利用 Go 的后端功能,我们使 AG-Grid 能够处理服务器端过滤、排序和分页,即使在处理大型数据集时也能确保流畅的性能。这种集成不仅优化了数据管理,还增强了前端动态、响应式表格的用户体验。通过 AG-Grid 和 Go 的协调工作,我们构建了一个非常适合实际应用的可扩展且高性能的网格系统。

源代码:https://github.com/stackpuz/Example-AG-Grid-Go

在几分钟内创建一个 CRUD Web 应用程序:https://stackpuz.com

以上是使用 Go 为 AG-Grid 创建 API的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:并发与原始速度Golang和C:并发与原始速度Apr 21, 2025 am 12:16 AM

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

为什么要使用Golang?解释的好处和优势为什么要使用Golang?解释的好处和优势Apr 21, 2025 am 12:15 AM

选择Golang的原因包括:1)高并发性能,2)静态类型系统,3)垃圾回收机制,4)丰富的标准库和生态系统,这些特性使其成为开发高效、可靠软件的理想选择。

Golang vs.C:性能和速度比较Golang vs.C:性能和速度比较Apr 21, 2025 am 12:13 AM

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

golang比C快吗?探索极限golang比C快吗?探索极限Apr 20, 2025 am 12:19 AM

Golang在编译时间和并发处理上表现更好,而C 在运行速度和内存管理上更具优势。1.Golang编译速度快,适合快速开发。2.C 运行速度快,适合性能关键应用。3.Golang并发处理简单高效,适用于并发编程。4.C 手动内存管理提供更高性能,但增加开发复杂度。

Golang:从Web服务到系统编程Golang:从Web服务到系统编程Apr 20, 2025 am 12:18 AM

Golang在Web服务和系统编程中的应用主要体现在其简洁、高效和并发性上。1)在Web服务中,Golang通过强大的HTTP库和并发处理能力,支持创建高性能的Web应用和API。2)在系统编程中,Golang利用接近硬件的特性和对C语言的兼容性,适用于操作系统开发和嵌入式系统。

Golang vs.C:基准和现实世界的表演Golang vs.C:基准和现实世界的表演Apr 20, 2025 am 12:18 AM

Golang和C 在性能对比中各有优劣:1.Golang适合高并发和快速开发,但垃圾回收可能影响性能;2.C 提供更高性能和硬件控制,但开发复杂度高。选择时需综合考虑项目需求和团队技能。

Golang vs. Python:比较分析Golang vs. Python:比较分析Apr 20, 2025 am 12:17 AM

Golang适合高性能和并发编程场景,Python适合快速开发和数据处理。 1.Golang强调简洁和高效,适用于后端服务和微服务。 2.Python以简洁语法和丰富库着称,适用于数据科学和机器学习。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!