我最终使用的另一个解决方案是go-geos,因为我发现我需要使用GEOS
C库。这样,我就可以将结构转换
WKT为要插入的结构(因为postgis将其作为常规文本接受)并可以
WKB在扫描时进行转换。
type Geometry4326 *geos.Geometry// Value converts the given Geometry4326 struct into WKT such that it can be stored in a // database. Implements Valuer interface for use with database operations.func (g Geometry4326) Value() (driver.Value, error) { str, err := g.ToWKT() if err != nil { return nil, err } return "SRID=4326;" + str, nil}// Scan converts the hexadecimal representation of geometry into the given Geometry4326 // struct. Implements Scanner interface for use with database operations.func (g *Geometry4326) Scan(value interface{}) error { bytes, ok := value.([]byte) if !ok { return errors.New("cannot convert database value to geometry") } str := string(bytes) geom, err := geos.FromHex(str) if err != nil { return errors.Wrap(err, "cannot get geometry from hex") } geometry := Geometry4326(geom) *g = geometry return nil}由于并非每个人都需要使用GEOS C库,因此该解决方案可能并不适合每个人,在Windows上工作可能会很痛苦。我敢肯定,使用不同的库可以完成同一件事。
我还在struct上实现了,
UnmarshalJSON()并
MarshalJSON()使其能够自动将GeoJSON编组/取消编组,然后无缝地从数据库保存/获取。我使用geojson-
go将GeoJSON与结构进行相互转换,然后使用geojson-
geos-go将上述结构转换为我正在使用的go-
geos结构,从而完成了此任务。有点令人费解,是的,但是有效。



