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

相关推荐
GetcharZp1 小时前
FileBrowser:用浏览器轻松管理服务器文件,简洁又强大
后端·go
前端熊猫11 小时前
为什么圆形在GeoJSON中被表示为多边形(Polygon)而不是圆形类型
geojson·polygon
帽儿山的枪手12 小时前
如何使用socket系统调用创建TCP三次握手呢?
网络协议·tcp/ip·go
行者无疆xcc21 小时前
【Go】重难点知识汇总
go
用户0142260029841 天前
golang开发环境搭建
go
Piper蛋窝1 天前
Go 1.13 相比 Go 1.12 有哪些值得注意的改动?
go
DemonAvenger1 天前
Go 并发利器:深入剖析 errgroup 的错误处理与最佳实践
分布式·架构·go
一个热爱生活的普通人1 天前
GIN 服务如何实现优雅停机
go·gin
yuanlaile1 天前
AI写代码之GO+Python写个爬虫系统
爬虫·python·go·ai编程
ifanatic1 天前
[每周一更]-(第140期):sync.Pool 使用详解:性能优化的利器
性能优化·go