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

相关推荐
MeetTanG16 小时前
Go 实战锦囊|errgroup:优雅地管理并发任务组
后端·go
名字还没想好☜17 小时前
Go 标准库 flag 包实战:参数解析、子命令、自定义 Value 类型与默认值
开发语言·后端·golang·go
天天喝旺仔20 小时前
gRPC 流式通信实战:从一元调用到双向流,吃透四种 RPC 模式(Go 版)
分布式·http·微服务·rpc·go
明月_清风1 天前
从二叉树到 B+ 树:一文搞懂工程中「树」的演化之道
数据结构·算法·go
江湖十年1 天前
在 Go 中使用 dyno 包处理动态对象
后端·面试·go
a187927218311 天前
【算法】回溯算法(三):三记重锤与 N 皇后——记忆化、状态设计与三层漏斗
算法·leetcode·go·剪枝·回溯·n皇后·算法讲解
纪卓志George1 天前
打破语言范式:在 Go 里用动态代理实现 AOP
架构·go
码艺-Alimjan2 天前
维吾尔语数字转文本
java·javascript·python·算法·go
名字还没想好☜2 天前
Go 时间格式化为什么用 2006-01-02:time.Format/Parse 的参考时间、时区与解析踩坑
开发语言·后端·golang·go
我的div丢了肿么办2 天前
go语言中的map,map定义不同的数据类型,循环map,map的无序性
后端·go