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. 结果图片

相关推荐
我的div丢了肿么办1 天前
go语言中的map,map定义不同的数据类型,循环map,map的无序性
后端·go
名字还没想好☜1 天前
Go 1.21 context.WithoutCancel 实战:父 context 取消了,收尾任务还要继续跑
开发语言·后端·golang·go
newerp1 天前
Golang 接口的两副面孔:eface、iface 与动态派发之谜
后端·程序员·go
明月_清风1 天前
递归算法:从原理到实战,一次讲透
后端·算法·go
运维开发笔记1 天前
9.1 Go Interface 基础知识学习笔记
go
a187927218311 天前
【算法】回溯算法(一):从一道 IP 题到万能模板
算法·leetcode·go·回溯·leetcode93·ip复原·算法讲解
gerrywhu1 天前
PostGIS实现DBSCAN空间聚类原理与应用实践【ST_ClusterDBSCAN】
聚类·postgis·dbscan·时空聚类·空间聚类分析·st_dbscan·postgis矢量数据分析
名字还没想好☜1 天前
Go 用 -race 抓数据竞争:一个偶发崩溃的排查、原理与修复
开发语言·后端·golang·go
gerrywhu2 天前
PostGIS实现KMeans空间聚类原理与应用实践【ST_ClusterKMeans】
聚类·postgis·k-means聚类·clusterkmeans·矢量数据分析·空间聚类·空间 k-means
Vespeng2 天前
打破传统 MVC:在 Go 中实践高内聚的业务驱动架构
架构·go·gin