AG-Grid 是一個(gè)功能強(qiáng)大的 JavaScript 數(shù)據(jù)網(wǎng)格庫,非常適合構(gòu)建具有排序、過濾和分頁等功能的動態(tài)高性能表格。在本文中,我們將在 Go 中創(chuàng)建一個(gè) API 來支持 AG-Grid,從而實(shí)現(xiàn)高效的服務(wù)器端數(shù)據(jù)操作,包括過濾、排序和分頁。通過將 AG-Grid 與 Go API 集成,我們將開發(fā)一個(gè)強(qiáng)大的解決方案,即使在處理大型數(shù)據(jù)集時(shí)也能確保平穩(wěn)的性能。
先決條件
- 去1.21
- MySQL
設(shè)置項(xiàng)目
設(shè)置 Go 項(xiàng)目依賴項(xiàng)。
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
創(chuàng)建名為“example”的測試數(shù)據(jù)庫,并運(yùn)行database.sql文件導(dǎo)入表和數(shù)據(jù)。
項(xiàng)目結(jié)構(gòu)
├─ .env ├─ main.go ├─ config │ └─ db.go ├─ controllers │ └─ product_controller.go ├─ models │ └─ product.go ├─ public │ └─ index.html └─ router └─ router.go
項(xiàng)目文件
.env
此文件包含數(shù)據(jù)庫連接信息。
DB_HOST=localhost DB_PORT=3306 DB_DATABASE=example DB_USER=root DB_PASSWORD=
數(shù)據(jù)庫Go
此文件使用 GORM 設(shè)置數(shù)據(jù)庫連接。它聲明了一個(gè)全局變量 DB 來保存數(shù)據(jù)庫連接實(shí)例,以便稍后在我們的應(yīng)用程序中使用。
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 應(yīng)用程序設(shè)置路由。它初始化 DataTables API 的路由器并在根 URL 處提供靜態(tài) 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() }
產(chǎn)品.go
此文件定義應(yīng)用程序的產(chǎn)品模型。
package models type Product struct { Id int Name string Price float64 }
產(chǎn)品控制器.go
此文件定義了一個(gè)函數(shù)來處理傳入請求并返回 DataTables 數(shù)據(jù)。
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 文件定義了一個(gè)控制器,用于使用 Gin 框架管理 Go 應(yīng)用程序中與產(chǎn)品相關(guān)的 API 請求。它具有一個(gè) Index 方法,可根據(jù)分頁、排序和搜索的查詢參數(shù)檢索分頁的產(chǎn)品列表。該方法提取分頁參數(shù),構(gòu)造查詢以從數(shù)據(jù)庫中獲取產(chǎn)品,并在提供搜索詞的情況下應(yīng)用過濾。在統(tǒng)計(jì)匹配產(chǎn)品總數(shù)后,它會對結(jié)果進(jìn)行排序和限制,然后返回包含產(chǎn)品數(shù)據(jù)和總數(shù)的 JSON 響應(yīng),以便于與前端應(yīng)用程序集成。
主程序
該文件是我們應(yīng)用程序的主要入口點(diǎn)。它將創(chuàng)建并設(shè)置 Gin Web 應(yīng)用程序。
package main import ( "app/config" "app/router" ) func main() { config.SetupDatabase() router.SetupRouter() }
索引.html
<!DOCTYPE html> <head> <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script> </head> <body> <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
打開網(wǎng)絡(luò)瀏覽器并轉(zhuǎn)到http://localhost:8080
你會發(fā)現(xiàn)這個(gè)測試頁。
測試
頁面大小測試
從“頁面大小”下拉列表中選擇 50 來更改頁面大小。每頁將顯示 50 條記錄,最后一頁將從 5 條變?yōu)?2 條。
分選測試
單擊第一列的標(biāo)題。您將看到 id 列將按降序排序。
搜索測試
在“名稱”欄的搜索文本框中輸入“否”,您將看到過濾后的結(jié)果數(shù)據(jù)。
結(jié)論
總之,我們有效地將 AG-Grid 與 Go API 集成,以創(chuàng)建強(qiáng)大且高效的數(shù)據(jù)網(wǎng)格解決方案。通過利用 Go 的后端功能,我們使 AG-Grid 能夠處理服務(wù)器端過濾、排序和分頁,即使在處理大型數(shù)據(jù)集時(shí)也能確保流暢的性能。這種集成不僅優(yōu)化了數(shù)據(jù)管理,還增強(qiáng)了前端動態(tài)、響應(yīng)式表格的用戶體驗(yàn)。通過 AG-Grid 和 Go 的協(xié)調(diào)工作,我們構(gòu)建了一個(gè)非常適合實(shí)際應(yīng)用的可擴(kuò)展且高性能的網(wǎng)格系統(tǒng)。
源代碼:https://github.com/stackpuz/Example-AG-Grid-Go
在幾分鐘內(nèi)創(chuàng)建一個(gè) CRUD Web 應(yīng)用程序:https://stackpuz.com
以上是使用 Go 為 AG-Grid 創(chuàng)建 API的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級代碼編輯軟件(SublimeText3)

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Golang主要用于后端開發(fā),但也能在前端領(lǐng)域間接發(fā)揮作用。其設(shè)計(jì)目標(biāo)聚焦高性能、并發(fā)處理和系統(tǒng)級編程,適合構(gòu)建API服務(wù)器、微服務(wù)、分布式系統(tǒng)、數(shù)據(jù)庫操作及CLI工具等后端應(yīng)用。雖然Golang不是網(wǎng)頁前端的主流語言,但可通過GopherJS編譯成JavaScript、通過TinyGo運(yùn)行于WebAssembly,或搭配模板引擎生成HTML頁面來參與前端開發(fā)。然而,現(xiàn)代前端開發(fā)仍需依賴JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能后端為核心的技術(shù)棧選擇。

要構(gòu)建一個(gè)GraphQLAPI在Go語言中,推薦使用gqlgen庫以提高開發(fā)效率。1.首先選擇合適的庫,如gqlgen,它支持根據(jù)schema自動生成代碼;2.接著定義GraphQLschema,描述API的結(jié)構(gòu)和查詢?nèi)肟冢缍xPost類型和查詢方法;3.然后初始化項(xiàng)目并生成基礎(chǔ)代碼,實(shí)現(xiàn)resolver中的業(yè)務(wù)邏輯;4.最后將GraphQLhandler接入HTTPserver,通過內(nèi)置Playground測試API。注意事項(xiàng)包括字段命名規(guī)范、錯(cuò)誤處理、性能優(yōu)化及安全設(shè)置等,確保項(xiàng)目可維護(hù)性

安裝Go的關(guān)鍵在于選擇正確版本、配置環(huán)境變量并驗(yàn)證安裝。1.前往官網(wǎng)下載對應(yīng)系統(tǒng)的安裝包,Windows使用.msi文件,macOS使用.pkg文件,Linux使用.tar.gz文件并解壓至/usr/local目錄;2.配置環(huán)境變量,在Linux/macOS中編輯~/.bashrc或~/.zshrc添加PATH和GOPATH,Windows則在系統(tǒng)屬性中設(shè)置PATH為Go的安裝路徑;3.使用goversion命令驗(yàn)證安裝,并運(yùn)行測試程序hello.go確認(rèn)編譯執(zhí)行正常。整個(gè)流程中PATH設(shè)置和環(huán)

Golang在構(gòu)建Web服務(wù)時(shí)CPU和內(nèi)存消耗通常低于Python。1.Golang的goroutine模型調(diào)度高效,并發(fā)請求處理能力強(qiáng),CPU使用率更低;2.Go編譯為原生代碼,運(yùn)行時(shí)不依賴虛擬機(jī),內(nèi)存占用更??;3.Python因GIL和解釋執(zhí)行機(jī)制,在并發(fā)場景下CPU和內(nèi)存開銷更大;4.雖然Python開發(fā)效率高、生態(tài)豐富,但資源消耗較高,適合并發(fā)要求不高的場景。

sync.WaitGroup用于等待一組goroutine完成任務(wù),其核心是通過Add、Done、Wait三個(gè)方法協(xié)同工作。1.Add(n)設(shè)置需等待的goroutine數(shù)量;2.Done()在每個(gè)goroutine結(jié)束時(shí)調(diào)用,計(jì)數(shù)減一;3.Wait()阻塞主協(xié)程直到所有任務(wù)完成。使用時(shí)需注意:Add應(yīng)在goroutine外調(diào)用、避免重復(fù)Wait、務(wù)必確保Done被調(diào)用,推薦配合defer使用。常見于并發(fā)抓取網(wǎng)頁、批量數(shù)據(jù)處理等場景,能有效控制并發(fā)流程。

使用Go的embed包可以方便地將靜態(tài)資源嵌入二進(jìn)制,適合Web服務(wù)打包HTML、CSS、圖片等文件。1.聲明嵌入資源需在變量前加//go:embed注釋,如嵌入單個(gè)文件hello.txt;2.可嵌入整個(gè)目錄如static/*,通過embed.FS實(shí)現(xiàn)多文件打包;3.開發(fā)時(shí)建議通過buildtag或環(huán)境變量切換磁盤加載模式以提高效率;4.注意路徑正確性、文件大小限制及嵌入資源的只讀特性。合理使用embed能簡化部署并優(yōu)化項(xiàng)目結(jié)構(gòu)。

WhenchoosingbetweenGolangandPythonforcodereadabilityandmaintainability,thedecisionhingesonteampriorities.1.Golangoffersstrictconsistencywithminimal,opinionatedsyntaxandbuilt-intoolinglikegofmt,ensuringuniformcodestyleandearlyerrordetection.2.Pythonpr
