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

相关推荐
一条GO1 天前
简单的 defer 也有可能写出BUG
go
用户580559502101 天前
深入理解 Go defer(下):编译器与runtime视角的实现原理
后端·go
tyung1 天前
用 zhenyi-base 做一个带网页的群聊 Demo
websocket·go
AntBlack1 天前
Ant-Browser : 发布一个开源免费的指纹浏览器 ,欢迎体验
后端·架构·go
程序员爱钓鱼1 天前
Go排序核心库: sort包深度指南
后端·面试·go
奔跑的呱呱牛2 天前
GeoJSON 在大数据场景下为什么不够用?替代方案分析
java·大数据·servlet·gis·geojson
ha6662 天前
golibs — Protocol & Registry 技术文档
go
程序员爱钓鱼2 天前
Go输出与格式化核心库:fmt包完整指南
后端·面试·go
贺小涛2 天前
Golang Gin框架核心原理与架构解析
架构·golang·gin
奔跑的呱呱牛2 天前
GeoJSON vs TopoJSON:不仅是体积差异,而是数据模型的差异
gis·geojson·topojson