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

相关推荐
10ms指针16 小时前
【高性能Go实践02】深水区重构:规避 sync.Pool 大对象缺陷与 Cgo 边界内存安全实践
go
鹏北海1 天前
Go 语言基础笔记 — 面向 JS/TS 前端开发者
go
鹏北海1 天前
Go 语言进阶笔记 — 面向 JS/TS 前端开发者
go
鹏北海1 天前
Go 包管理笔记 — 面向 JS/TS 前端开发者
go
百度Geek说2 天前
告别死锁和陈旧语法、告别性能瓶颈:新手Gopher 秒变 Go 语言大神
人工智能·go
用户398346161202 天前
Go-Spring 实战第 14 课 —— Bean 注册函数:Provide、Module、Group 以及 Configuration
spring·go
锋行天下2 天前
一句mysql复杂查询搞崩一个壮汉
后端·mysql·go
用户398346161203 天前
Go-Spring 实战第 13 课 —— Bean 元信息:名称、生命周期、接口导出、条件和显式依赖
spring·go
猪猪拆迁队3 天前
用 ESP32-S3 和 TinyGo,先搭个 AI 语音助手的小底座
前端·后端·go
赫媒派4 天前
炸裂!Go 1.26 三连发:go fix 现代化、pkg.go.dev API 开放、源码级内联器
go