go gin gorm连接postgres postgis输出geojson

go gin gorm连接postgres postgis输出geojson

1. 技术环境

go-gin-gorm

postgres-postgis

go vscode环境安装-智能提示配置

2. 简单实现代码

思路就是:采用原生sql实现查询、更新等,采用gorm的raw来执行sql语句

Go 复制代码
package main

import (
	"fmt"
	"net/http"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)
// 前提是在postgres中安装好postgis插件
func main() {
	dsn := "host=localhost user=postgres password=5241 dbname=test port=5432 sslmode=disable TimeZone=Asia/Shanghai"
	db, _ := gorm.Open(postgres.New(postgres.Config{
		DSN:                  dsn,
		PreferSimpleProtocol: true,
	}), &gorm.Config{})

	r := gin.Default()
	r.GET("/data/:table_name", func(c *gin.Context) {
		table_name := c.Param("table_name")
        // 从postgis中利用 ST 函数 获得的结果,以string返回,然后前端进行解析即可
		var result string
		
		if db.Migrator().HasTable(table_name) {
			sqls := fmt.Sprintf("select json_build_object('type', 'FeatureCollection', 'name', '%s', 'features', json_agg(ST_ASGeoJSON(t.*)::json)) from %s AS t", table_name, table_name)
			db.Raw(sqls).Scan(&result)
		}
		fmt.Printf("%q", result)

		c.JSON(http.StatusOK, gin.H{
			"message": "ok",
			"data":    result,
		})
	})
	r.Run(":8080")
}

3. 结果图片

相关推荐
踏着七彩祥云的小丑12 小时前
Go学习第1天:入门
开发语言·学习·golang·go
gerrywhu17 小时前
PostGIS强大栅格分析工具-栅格代数运算(回调函数版)【ST_MapAlgebra 】
postgis·回调函数·栅格数据分析·栅格代数·st_mapalgebra·栅格回调函数·栅格加权
TE-茶叶蛋21 小时前
B-tree vs GIN Trigram vs HNSW
gin
用户743835613512 天前
无锁 Hub:我的 IM 系统为什么用 channel 而不是 mutex 管理在线用户
go
吴佳浩3 天前
Go史上最大“打脸”现场来了:泛型方法终于实现了
后端·go
明月_清风3 天前
深入 Go 并发编程:从 Goroutine 到 Channel 的系统性避坑指南
后端·go
曾几何时`3 天前
Go(一)Gin框架 和 GORM机制
开发语言·golang·gin
用户34232323763174 天前
开源!Go+Wails+Vue3 手搓一个 PLC 实时监控桌面工具
go
止语Lab4 天前
为什么你的 Go TCP server P99 延迟这么高
go