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

相关推荐
用户1257585243627 分钟前
Go 里读取 request body 后,下游拿不到参数:别让日志中间件把请求吃掉
http·go·测试
tyung20 小时前
zhenyi-base zqueue 基准测试分享
后端·go
香吧香20 小时前
go tool pprof 使用总结二
go
用户6757049885021 天前
写了 6 年 Go ,我终于领悟到了泛型的真正威力!
后端·go
名字还没想好☜1 天前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理
bulldozer2 天前
写了个零依赖的 Go 版本管理器,curl | bash 完事
go
香吧香2 天前
go tool pprof 使用总结
go
用户6757049885022 天前
从失真到绝对精准:Go语言中如何进行高精度计算?
后端·go
用户6757049885022 天前
还在用字符串返回错误提示?Go语言优雅错误处理的正确姿势!
后端·go
唐青枫2 天前
别把 CLI 写成一坨 os.Args:Go Cobra 从命令树到实战工具详解
go