Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.vscode
data/
!data/postcodes
!data/codepo_gb.zip
LICENSE.md
README.md
ATTRIBUTION.md
Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ RUN apk --no-cache add curl ca-certificates tzdata && \
RUN adduser -D -g '' appuser
WORKDIR /app

COPY ./data/codepo_gb.zip /app/data/codepo_gb.zip
COPY ./data/postcodes /app/data/postcodes
COPY --from=build /app/postcode-polygons .
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
Expand Down
Binary file added data/codepo_gb.zip
Binary file not shown.
71 changes: 67 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,77 @@ module postcode-polygons

go 1.24.4

require github.com/paulmach/orb v0.11.1
require (
github.com/Depado/ginprom v1.8.1
github.com/aurowora/compress v0.0.0-20230724224640-6512772d482f
github.com/gin-contrib/cors v1.7.6
github.com/gin-gonic/gin v1.10.1
github.com/paulmach/orb v0.11.1
github.com/spf13/cobra v1.9.1
github.com/tavsec/gin-healthcheck v1.7.8
go.eigsys.de/gin-cachecontrol/v2 v2.3.0
)

require (
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bytedance/sonic v1.13.3 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.26.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/influxdata/influxdb-client-go/v2 v2.14.0 // indirect
github.com/influxdata/line-protocol v0.0.0-20210922203350-b1ad95c89adf // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/oapi-codegen/runtime v1.1.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/prometheus/client_golang v1.22.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.64.0 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/rabbitmq/amqp091-go v1.10.0 // indirect
github.com/redis/go-redis/v9 v9.10.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/tidwall/geoindex v1.7.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
golang.org/x/arch v0.18.0 // indirect
golang.org/x/crypto v0.39.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sync v0.15.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

require (
github.com/dsnet/compress v0.0.1
github.com/dustin/go-humanize v1.0.1
github.com/fatih/color v1.18.0 // indirect
github.com/fatih/color v1.18.0
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
go.mongodb.org/mongo-driver v1.11.4 // indirect
golang.org/x/sys v0.25.0 // indirect
github.com/tidwall/rtree v1.10.0
go.mongodb.org/mongo-driver v1.17.4 // indirect
golang.org/x/sys v0.33.0 // indirect
)
303 changes: 300 additions & 3 deletions go.sum

Large diffs are not rendered by default.

79 changes: 77 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,84 @@
package main

import (
"postcode-polygons/extraction"
"fmt"
"log"
"os"
"postcode-polygons/routes"
spatialindex "postcode-polygons/spatial-index"

"github.com/Depado/ginprom"
"github.com/aurowora/compress"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
healthcheck "github.com/tavsec/gin-healthcheck"
"github.com/tavsec/gin-healthcheck/checks"
hc_config "github.com/tavsec/gin-healthcheck/config"
cachecontrol "go.eigsys.de/gin-cachecontrol/v2"
)

func main() {
extraction.Extract("./data/gb-postcodes-v5.tar.bz2")
var err error
var zipFile string
var port int

rootCmd := &cobra.Command{
Use: "http",
Short: "Postcode Polygons API server",
Run: func(cmd *cobra.Command, args []string) {
server(zipFile, port)
},
}

rootCmd.Flags().StringVar(&zipFile, "codepoint", "./data/codepo_gb.zip", "Path to CodePoint Open zip file")
rootCmd.Flags().IntVar(&port, "port", 8080, "Port to run HTTP server on")

if err = rootCmd.Execute(); err != nil {
log.Fatalf("failed to execute root command: %v", err)
}
}

func server(zipFile string, port int) {
if _, err := os.Stat(zipFile); os.IsNotExist(err) {
log.Fatalf("CodePoint zip file does not exist: %s", zipFile)
}

log.Printf("Loading CodePoint data from: %s", zipFile)
spatialIndex, err := spatialindex.NewCodePointSpatialIndex(zipFile)
if err != nil {
log.Fatalf("failed to create spatial index: %v", err)
}
log.Printf("CodePoint spatial index created with %d entries", spatialIndex.Len())

r := gin.New()

prometheus := ginprom.New(
ginprom.Engine(r),
ginprom.Namespace("postcode_polygons"),
ginprom.Subsystem("api"),
ginprom.Path("/metrics"),
ginprom.Ignore("/healthz"),
)

r.Use(
gin.Recovery(),
gin.LoggerWithWriter(gin.DefaultWriter, "/healthz", "/metrics"),
prometheus.Instrument(),
compress.Compress(),
cachecontrol.New(cachecontrol.CacheAssetsForeverPreset),
cors.Default(),
)

err = healthcheck.New(r, hc_config.DefaultConfig(), []checks.Check{})
if err != nil {
log.Fatalf("failed to initialize healthcheck: %v", err)
}

r.GET("/v1/postcode/search", routes.Search(spatialIndex))

addr := fmt.Sprintf(":%d", port)
log.Printf("Starting HTTP API Server on port %d...", port)
err = r.Run(addr)
log.Fatalf("HTTP API Server failed to start on port %d: %v", port, err)
Comment on lines +82 to +83

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Check specifically for http.ErrServerClosed to avoid logging a fatal error during graceful shutdowns. Import "net/http" to use this.

	if err := r.Run(addr); err != nil && err != http.ErrServerClosed {
		log.Fatalf("HTTP API Server failed on port %d: %v", port, err)
	}

}
8 changes: 8 additions & 0 deletions routes/attribution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package routes

var ATTRIBUTION = []string{
"CodePoint Open (UK Gov, OS Data Hub), https://osdatahub.os.uk/downloads/open/CodePointOpen",
"Mark Longair's Blog, https://longair.net/blog/2021/08/23/open-data-gb-postcode-unit-boundaries/",
"Derived content from: Office for National Statistics licensed under the Open Government Licence v.3.0",
"Derived content from: Royal Mail data © Royal Mail copyright and database right 2020",
}
68 changes: 68 additions & 0 deletions routes/search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package routes

import (
"fmt"
"log"
"math"
"net/http"
spatialindex "postcode-polygons/spatial-index"
"strconv"
"strings"

"github.com/gin-gonic/gin"
)

type SearchResponse struct {
Results []spatialindex.CodePoint `json:"results"`
Attribution []string `json:"attribution"`
}

const MAX_BOUNDS = 5000 // Maximum bounds in meters (5 KM)

func Search(spatialIndex *spatialindex.SpatialIndex) func(c *gin.Context) {
return func(c *gin.Context) {
bbox, err := parseBBox(c.Query("bbox"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

results, err := spatialIndex.Search(bbox)
if err != nil {
log.Printf("error while fetching postcode data: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "An internal server error occurred"})
return
}

c.JSON(http.StatusOK, SearchResponse{
Results: *results,
Attribution: ATTRIBUTION,
})
}
}

func parseBBox(bboxStr string) ([]uint32, error) {
bboxParts := strings.Split(bboxStr, ",")
if len(bboxParts) != 4 {
return nil, fmt.Errorf("bbox must have 4 comma-separated values")
}

bbox := make([]uint32, 4)
for i, part := range bboxParts {
val, err := strconv.ParseUint(strings.TrimSpace(part), 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid bbox value '%s': not a valid float", part)
}
bbox[i] = uint32(val)
}

if bbox[0] > bbox[2] || bbox[1] > bbox[3] {
return nil, fmt.Errorf("invalid bbox: min values must be less than or equal to max values")
}

if math.Abs(float64(bbox[2]-bbox[0])) > MAX_BOUNDS || math.Abs(float64(bbox[3]-bbox[1])) > MAX_BOUNDS {
return nil, fmt.Errorf("bbox must define a valid area (no more than %d KM in either dimension)", MAX_BOUNDS/1000)
}
Comment thread
rm-hull marked this conversation as resolved.

return bbox, nil
}
125 changes: 125 additions & 0 deletions spatial-index/codepoint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package spatialindex

import (
"archive/zip"
"fmt"
"log"
"strconv"
"strings"

"github.com/tidwall/rtree"
)

type CodePoint struct {
PostCode string `json:"post_code"`
Easting uint32 `json:"easting"`
Northing uint32 `json:"northing"`
}

type SpatialIndex struct {
tree *rtree.RTreeGN[uint32, string]
}

func (idx *SpatialIndex) Search(bounds []uint32) (*[]CodePoint, error) {
if len(bounds) != 4 {
return nil, fmt.Errorf("search bounds must contain exactly 4 values: min_easting, min_northing, max_easting, max_northing")
}

sw := [2]uint32{bounds[0], bounds[1]} // South-West corner
ne := [2]uint32{bounds[2], bounds[3]} // North-East corner

results := make([]CodePoint, 0, 100)
idx.tree.Search(sw, ne, func(min, max [2]uint32, data string) bool {
results = append(results, CodePoint{
PostCode: data,
Easting: min[0],
Northing: min[1],
})
return true
})

return &results, nil
}

func NewCodePointSpatialIndex(zipFile string) (*SpatialIndex, error) {
idx := SpatialIndex{
tree: &rtree.RTreeGN[uint32, string]{},
}

err := idx.importCodePoint(zipFile)
if err != nil {
return nil, fmt.Errorf("failed to load codepoint index from zip file: %w", err)
}

return &idx, nil
}

func (idx *SpatialIndex) Len() int {
return idx.tree.Len()
}

func (idx *SpatialIndex) importCodePoint(zipPath string) error {

r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open zip file: %w", err)
}
defer func() {
if err := r.Close(); err != nil {
log.Printf("error closing zip file: %v", err)
}
}()

for _, f := range r.File {
if f.FileInfo().IsDir() || !strings.HasPrefix(f.Name, "Data/CSV/") {
continue
}

if err := idx.processCSV(f); err != nil {
return fmt.Errorf("failed to process CSV data: %w", err)
}
}
return nil
}

func (idx *SpatialIndex) processCSV(f *zip.File) error {
r, err := f.Open()
if err != nil {
return fmt.Errorf("failed to open embedded file %s in zip: %w", f.Name, err)
}
defer func() {
if err := r.Close(); err != nil {
log.Printf("error closing embedded zip file: %v", err)
}
}()

for result := range parseCSV(r, false, fromCodePointCSV) {

if result.Error != nil {
return fmt.Errorf("error parsing line %d: %w", result.LineNum, result.Error)
}

point := [2]uint32{uint32(result.Value.Easting), uint32(result.Value.Northing)}
idx.tree.Insert(point, point, result.Value.PostCode)
}

return nil
}

func fromCodePointCSV(record []string, headers []string) (*CodePoint, error) {

easting, err := strconv.ParseUint(record[2], 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid easting value: %w", err)
}
northing, err := strconv.ParseUint(record[3], 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid northing value: %w", err)
}

return &CodePoint{
PostCode: record[0],
Easting: uint32(easting),
Northing: uint32(northing),
}, nil
}
Loading