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
36 changes: 36 additions & 0 deletions .github/workflows/changelog.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: Update Changelog

on:
push:
branches:
- main
release:
types: [published]
workflow_dispatch:

permissions:
contents: write

jobs:
changelog:
name: Update Changelog
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Generate Changelog
uses: orhun/git-cliff-action@v4
with:
config: cliff.toml
args: --verbose
env:
OUTPUT: CHANGELOG.md

- name: Commit
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "chore(changelog): update changelog"
file_pattern: CHANGELOG.md
10 changes: 0 additions & 10 deletions .golangci.yml

This file was deleted.

9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Changelog

All notable changes to this project will be documented in this file.

## [unreleased]

### Miscellaneous Tasks

- Initial changelog setup
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ WhereGo is designed for high performance and low resource usage.
## Roadmap

- [ ] automation to update the database
- [ ] Increase test coverage
- [x] Increase test coverage
- [ ] gRPC endpoint
- [ ] Built-in rate limiting

Expand Down
79 changes: 79 additions & 0 deletions cliff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# git-cliff ~ default configuration file
# https://git-cliff.org/docs/configuration
#
# Lines starting with "#" are comments.

[changelog]
# template for the changelog header
header = """
# Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://keats.github.io/tera/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | striptags | trim | upper_first }}
{% for commit in commits %}
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
{% if commit.breaking %}[**breaking**] {% endif %}\
{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# template for the changelog footer
footer = """
<!-- generated by git-cliff -->
"""
# remove the leading and trailing s
trim = true

[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = false
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
# { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](<REPO>/issues/${2}))"},
# Check spelling of the commit with https://github.com/crate-ci/typos
# { pattern = '.*', replace_command = 'typos --write-changes -' },
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "<!-- 0 -->Features" },
{ message = "^fix", group = "<!-- 1 -->Bug Fixes" },
{ message = "^doc", group = "<!-- 3 -->Documentation" },
{ message = "^perf", group = "<!-- 4 -->Performance" },
{ message = "^refactor", group = "<!-- 2 -->Refactor" },
{ message = "^style", group = "<!-- 5 -->Styling" },
{ message = "^test", group = "<!-- 6 -->Testing" },
{ message = "^chore\\(release\\): prepare for", skip = true },
{ message = "^chore\\(deps.*\\)", skip = true },
{ message = "^chore\\(pr\\)", skip = true },
{ message = "^chore\\(pull\\)", skip = true },
{ message = "^chore|^ci", group = "<!-- 7 -->Miscellaneous Tasks" },
{ body = ".*security", group = "<!-- 8 -->Security" },
{ message = "^revert", group = "<!-- 9 -->Revert" },
]
# protect breaking changes from being skipped due to matching a skipping commit_parser
protect_breaking_commits = false
# filter out the commits that are not matched by commit parsers
filter_commits = false
# regex for matching git tags
tag_pattern = "v[0-9].*"
# regex for skipping tags
# skip_tags = ""
# regex for ignoring tags
# ignore_tags = ""
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
25 changes: 17 additions & 8 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,11 @@ import (

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func main() {
geoService, err := geoip.NewService("data/city.db")
func NewServer(dbPath string) (*echo.Echo, *geoip.Service, error) {
geoService, err := geoip.NewService(dbPath)
if err != nil {
log.Fatalf("Failed to initialize GeoIP service: %v", err)
return nil, nil, err
}
defer func() {
if err := geoService.DB.Close(); err != nil {
log.Printf("Failed to close GeoIP database: %v", err)
}
}()

handler := &handlers.GeoIPHandler{
GeoService: geoService,
Expand All @@ -35,6 +30,20 @@ func main() {
e.GET("/health", handlers.HealthCheck)
e.GET("/lookup/:ip", handler.Lookup)

return e, geoService, nil
}

func main() {
e, geoService, err := NewServer("data/city.db")
if err != nil {
log.Fatalf("Failed to initialize GeoIP service: %v", err)
}
defer func() {
if err := geoService.DB.Close(); err != nil {
log.Printf("Failed to close GeoIP database: %v", err)
}
}()

port := os.Getenv("PORT")
if port == "" {
port = "8080"
Expand Down
151 changes: 151 additions & 0 deletions cmd/api/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package main

import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"testing"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// TestJSONSerializer_Serialize covers serialization scenarios using a table-driven approach.
func TestJSONSerializer_Serialize(t *testing.T) {
e := echo.New()
serializer := &JSONSerializer{}
e.JSONSerializer = serializer

tests := []struct {
name string
input interface{}
indent string
expectedBody string
}{
{
name: "Default Serialization",
input: map[string]string{"hello": "world"},
indent: "",
expectedBody: `{"hello":"world"}`,
},
{
name: "Indented Serialization",
input: map[string]string{"hello": "world"},
indent: " ",
expectedBody: "{\n \"hello\": \"world\"\n}\n",
},
{
name: "Complex Struct",
input: struct{ ID int }{ID: 1},
indent: "",
expectedBody: `{"ID":1}`,
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

err := serializer.Serialize(c, tc.input, tc.indent)
assert.NoError(t, err)
assert.JSONEq(t, tc.expectedBody, rec.Body.String())
})
}
}

// TestJSONSerializer_Deserialize covers deserialization scenarios.
func TestJSONSerializer_Deserialize(t *testing.T) {
e := echo.New()
serializer := &JSONSerializer{}
e.JSONSerializer = serializer

t.Run("Success", func(t *testing.T) {
jsonBody := `{"hello":"world"}`
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(jsonBody))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

var result map[string]string
err := serializer.Deserialize(c, &result)
require.NoError(t, err)
assert.Equal(t, "world", result["hello"])
})

t.Run("Malformed JSON", func(t *testing.T) {
jsonBody := `{"hello":` // Invalid JSON
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(jsonBody))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

var result map[string]string
err := serializer.Deserialize(c, &result)
assert.Error(t, err)
})
}

func TestNewServer(t *testing.T) {
dbPath := "../../data/city.db"

t.Run("Success Initialization", func(t *testing.T) {
// Check if file exists before trying, to avoid failing in CI environments without the DB.
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
t.Skipf("Skipping test: Database file not found at %s", dbPath)
}

e, svc, err := NewServer(dbPath)
require.NoError(t, err)
require.NotNil(t, e)
require.NotNil(t, svc)

// Clean up
svcErr := svc.DB.Close()
require.NoError(t, svcErr)

// Verify Routes are Registered
foundRoutes := 0
for _, r := range e.Routes() {
if r.Path == "/health" && r.Method == http.MethodGet {
foundRoutes++
}
if r.Path == "/lookup/:ip" && r.Method == http.MethodGet {
foundRoutes++
}
}
assert.Equal(t, 2, foundRoutes, "Expected /health and /lookup/:ip routes to be registered")
})

t.Run("Failure Invalid Path", func(t *testing.T) {
e, svc, err := NewServer("invalid/path/to/db.mmdb")
assert.Error(t, err)
assert.Nil(t, e)
assert.Nil(t, svc)
})
}

func TestHealthCheck_Integration(t *testing.T) {
dbPath := "../../data/city.db"
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
t.Skip("Skipping integration test: Database not found")
}

e, svc, err := NewServer(dbPath)
require.NoError(t, err)
defer func() {
closeErr := svc.DB.Close()
require.NoError(t, closeErr)
}()

req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()

// Inject request into Echo
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "status")
}
51 changes: 0 additions & 51 deletions internal/geoip/reader.go
Original file line number Diff line number Diff line change
@@ -1,54 +1,3 @@
// Package geoip2 provides an easy-to-use API for the MaxMind GeoIP2 and
// GeoLite2 databases; this package does not support GeoIP Legacy databases.
//
// # Basic Usage
//
// db, err := geoip2.Open("GeoIP2-City.mmdb")
// if err != nil {
// log.Fatal(err)
// }
// defer db.Close()
//
// ip, err := netip.ParseAddr("81.2.69.142")
// if err != nil {
// log.Fatal(err)
// }
//
// record, err := db.City(ip)
// if err != nil {
// log.Fatal(err)
// }
//
// if !record.HasData() {
// fmt.Println("No data found for this IP")
// return
// }
//
// fmt.Printf("City: %v\n", record.City.Names.English)
// fmt.Printf("Country: %v\n", record.Country.Names.English)
//
// # Database Types
//
// This library supports all MaxMind database types:
// - City: Most comprehensive geolocation data
// - Country: Country-level geolocation
// - ASN: Autonomous system information
// - AnonymousIP: Anonymous network detection
// - Enterprise: Enhanced City data with additional fields
// - ISP: Internet service provider information
// - Domain: Second-level domain data
// - ConnectionType: Connection type identification
//
// # Version 2.0 Features
//
// Version 2.0 introduces significant improvements:
// - Modern API using netip.Addr instead of net.IP
// - Network and IPAddress fields in all result structs
// - HasData() method for data validation
// - Structured Names type for localized names
// - JSON serialization support
//
// See github.com/oschwald/maxminddb-golang/v2 for more advanced use cases.
package geoip

import (
Expand Down
Loading