Golang: Scanning MySQL/MariaDB geographical Point type

Let’s say you build own Google Maps in Golang with MariaDB and would like to store ‘Favorite’ points on the map in the database. This article will demonstrate to you how to do that, relying on Sqlx library.

Sqlx is a package written for Go which among other features provides a standardised way to query the database and collect query results in models and vice versa. There is no built-in scanner for MySQL/MariaDB Geo Point type.

The database doesn’t store Point in public formats such as WKT or WKB, but in internal, AsBinary, AsWKB functions convert internal format in public ones. Finding out how a type Point is stored, the first bytes represent SRID, ordering, geometry type. After query performed, MySQL driver returns a byte sequence with length 25. Last 16 bytes represent location points.

Scan method being called on the structure, this is the place for a custom function. driver. Valuer interface may be used for deserialization (before writing an object in a database).

That’s the actual piece of the code. The function is not adapted for other Geometric types than Point, but rather expandable. Go provides an extremely minimalist way to Scan custom types.