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

相关推荐
stark张宇41 分钟前
Go语言核心三剑客:数组、切片与结构体使用指南
后端·go
Aevget1 小时前
智能高效Go开发工具GoLand v2025.3全新上线——新增资源泄漏分析
开发语言·ide·后端·golang·go
wwz168 小时前
Dagor —— 一个高性能 DAG 算子执行框架,开箱即用!
go
源代码•宸8 小时前
goframe框架签到系统项目开发(补签逻辑实现、编写Lua脚本实现断签提醒功能、简历示例)
数据库·后端·中间件·go·lua·跨域·refreshtoken
光头闪亮亮1 天前
Go语言开发的命令行MP3播放器
go
Grassto1 天前
Go Module 的版本选择算法:Minimal Version Selection(MVS)
后端·golang·go·go module
天天向上10241 天前
在 Go 的 Gin Web 框架中,获取 HTTP 请求参数有多种方式
前端·golang·gin
汪小成2 天前
Go CLI 入口设计:参数解析、错误处理与项目分层实战
后端·go
gitboyzcf2 天前
Go(GoLang)语言基础、知识速查
后端·go
汪小成3 天前
Go 项目结构总是写乱?这个 50 行代码的 Demo 教你标准姿势
后端·go