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

相关推荐
烛阴1 天前
Go 语言进阶:打造可复用的模块,导出你的专属包
后端·go
GIS小小研究僧2 天前
PostgreSQL 数据库备份与还原
数据库·postgresql·oracle·postgis
gopher_looklook3 天前
从零到一: 用Go语言搭建简易RPC框架并实践 (一)
后端·go
龙雨LongYu124 天前
go gin配置air
开发语言·golang·gin
猫九森4 天前
go 循环处理无限极数据
数据结构·后端·go
川Princess5 天前
【后端开发】字节跳动青训营Cloudwego脚手架
go·字节跳动青训营·cwgo
梦想画家5 天前
Golang Gin系列-9:Gin 集成Swagger生成文档
golang·gin·swagger
zhoupenghui1685 天前
golang通过AutoMigrate方法自动创建table详解
数据库·gorm·automigrate
梦想画家5 天前
Golang Gin系列-7:认证和授权
golang·gin·授权认证
Super毛毛穗6 天前
GeoJSON 数据
javascript·gis·geojson