Browse Source

Initial commit

Volodymyr Tkach 2 years ago
parent
commit
35ac5b687d

+ 13 - 0
.dockerignore

@@ -0,0 +1,13 @@
+.git
+.makefile
+build
+cmd
+internal
+.dockerignore
+.gitignore
+Dockerfile
+LICENSE
+Makefile
+README.md
+go.mod
+go.sum

+ 6 - 0
.gitignore

@@ -0,0 +1,6 @@
+/bin/*
+!/bin/.keep
+/build/*
+!/build/.keep
+/data/*
+!/data/.keep

+ 19 - 0
.makefile/build.makefile

@@ -0,0 +1,19 @@
+BINARIES=$(patsubst cmd/%/main.go,bin/%,$(wildcard cmd/*/main.go))
+STATIC_BINARIES=$(patsubst cmd/%/main.go,bin/%-static,$(wildcard cmd/*/main.go))
+
+all: $(BINARIES)
+static: $(STATIC_BINARIES)
+
+.PHONY: all static
+
+GO_SOURCES=
+GO_SOURCES+=$(shell find . -name '*.go' -not -path '*vendor*' -not -path '*.pb.go')
+GO_SOURCES+=$(wildcard go.*)
+
+bin/%: cmd/%/main.go $(GO_SOURCES)
+	@mkdir -p $(dir $@)
+	go build -o $@ $<
+
+bin/%-static: cmd/%/main.go $(GO_SOURCES)
+	@mkdir -p $(dir $@)
+	CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -a -ldflags '-extldflags "-static"' -o $@ $<

+ 20 - 0
.makefile/docker.makefile

@@ -0,0 +1,20 @@
+docker-build: all
+	@-docker rmi ${DOCKER_IMG_NAME}:latest
+	docker build -t ${DOCKER_IMG_NAME}:latest ./
+
+docker-export:
+	@-rm ./build/${DOCKER_IMG_NAME}.tar
+	docker save ${DOCKER_IMG_NAME}:latest > ./build/${DOCKER_IMG_NAME}.tar
+
+docker-import:
+	@-docker rmi ${DOCKER_IMG_NAME}:latest
+	docker load < ./build/${DOCKER_IMG_NAME}.tar
+
+docker-push: docker-build
+	docker tag ${DOCKER_IMG_NAME}:latest vladimirok5959/${DOCKER_IMG_NAME}:${VERSION}
+	docker tag ${DOCKER_IMG_NAME}:latest vladimirok5959/${DOCKER_IMG_NAME}:latest
+	docker login
+	docker push vladimirok5959/${DOCKER_IMG_NAME}:${VERSION}
+	docker push vladimirok5959/${DOCKER_IMG_NAME}:latest
+	docker rmi vladimirok5959/${DOCKER_IMG_NAME}:${VERSION}
+	docker rmi vladimirok5959/${DOCKER_IMG_NAME}:latest

+ 16 - 0
.makefile/minimal.makefile

@@ -0,0 +1,16 @@
+test:
+	go test ./...
+
+bench:
+	go test ./... -run=NONE -bench=. -benchmem
+
+staticcheck:
+	staticcheck ./...
+
+lint:
+	golangci-lint run
+
+tidy:
+	go mod tidy
+
+.PHONY: test bench staticcheck tidy

+ 29 - 0
Dockerfile

@@ -0,0 +1,29 @@
+FROM debian:latest
+MAINTAINER Volodymyr Tkach <vladimirok5959@gmail.com>
+
+ENV ENV_HOST=127.0.0.1 ENV_PORT=8080 ENV_DATA_DIR=/app/data
+
+COPY ./bin/ip2location /app/app
+
+ARG DEBIAN_FRONTEND=noninteractive
+
+RUN apt-get -y update && \
+    apt-get -y upgrade && \
+    apt-get install -y curl ca-certificates && \
+    dpkg-reconfigure -p critical ca-certificates && \
+    echo "" >> /root/.profile && \
+    echo "TIME_ZONE=\$(cat /etc/timezone)" >> /root/.profile && \
+    echo "export TZ=\"\${TIME_ZONE}\"" >> /root/.profile && \
+    echo "" >> /root/.bashrc && \
+    echo "TIME_ZONE=\$(cat /etc/timezone)" >> /root/.bashrc && \
+    echo "export TZ=\"\${TIME_ZONE}\"" >> /root/.bashrc && \
+    mkdir /app/data && \
+    mkdir /app/logs && \
+    chmod +x /app/app
+
+HEALTHCHECK --interval=30s --timeout=5s --start-period=5s CMD curl --fail http://localhost:$ENV_PORT/api/v1/app/health || exit 1
+
+EXPOSE 8080
+VOLUME /app/data
+
+CMD export TZ="$(cat /etc/timezone)" && /app/app

+ 41 - 0
Makefile

@@ -0,0 +1,41 @@
+VERSION="1.0.0"
+DOCKER_IMG_NAME := golang-ip2location
+CURRENT_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
+DATA_DIR := ${CURRENT_DIR}/data
+
+.PHONY: default
+default: test
+
+include .makefile/minimal.makefile
+include .makefile/build.makefile
+include .makefile/docker.makefile
+
+test:
+	go test `go list ./... \
+		| grep -v cmd/ip2location \
+		| grep -v internal/consts \
+		| grep -v internal/server/web`
+
+debug:
+	@-rm ./bin/ip2location
+	make all
+	./bin/ip2location \
+		-data_dir ${DATA_DIR} \
+		-deployment development \
+		-host 0.0.0.0 \
+		-port 8080 \
+		-web_url http://localhost:8080/ \
+		color=always
+
+docker-test:
+	docker run --rm \
+		--network host \
+		--name ${DOCKER_IMG_NAME}-test \
+		-e ENV_DATA_DIR="/app/data" \
+		-e ENV_DEPLOYMENT="deployment" \
+		-e ENV_HOST="127.0.0.1" \
+		-e ENV_PORT="8080" \
+		-e ENV_WEB_URL="http://localhost:8080/" \
+		-v /etc/timezone:/etc/timezone:ro \
+		-v ${CURRENT_DIR}/data:/app/data \
+		-it ${DOCKER_IMG_NAME}:latest

+ 71 - 1
README.md

@@ -1,2 +1,72 @@
 # golang-ip2location
-For self hosted, ready to use RESTful API microservice for converting IP to location
+
+For self hosted, ready to use RESTful API microservice for converting IP to location such a `City`, `Country`and `Region`. Free lite database version of `ip2location.com` is used. Please donwload your own database file from `ip2location.com`. You can also use `db-update.sh` script in the root directory for automatically refreshing database from `ip2location.com` with your own token. You can download databsae here [https://lite.ip2location.com/database-download](https://lite.ip2location.com/database-download)
+
+Docker image: [https://hub.docker.com/r/vladimirok5959/golang-ip2location](https://hub.docker.com/r/vladimirok5959/golang-ip2location)
+
+## Usage
+
+```sh
+Usage of ./ip2location:
+  -access_log_file string
+    Or ENV_ACCESS_LOG_FILE: Access log file
+  -data_dir string
+    Or ENV_DATA_DIR: Application data directory
+  -deployment string
+    Or ENV_DEPLOYMENT: Deployment type (default "development")
+  -error_log_file string
+    Or ENV_ERROR_LOG_FILE: Error log file
+  -host string
+    Or ENV_HOST: Web server IP (default "127.0.0.1")
+  -port string
+    Or ENV_PORT: Web server port (default "8080")
+  -web_url string
+    Or ENV_WEB_URL: Web server home URL (default "http://localhost:8080/")
+```
+
+## API endpoint
+
+Only one: http://localhost:8080/api/v1/ip2location/8.8.8.8
+
+```txt
+HTTP/1.1 200 OK
+Content-Type: application/json
+Date: Thu, 12 Oct 2022 20:45:48 GMT
+Content-Length: 107
+```
+
+```json
+{
+    "City": "Mountain View",
+    "CountryLong": "United States of America",
+    "CountryShort": "US",
+    "Region": "California"
+}
+```
+
+## DB auto update
+
+Right now, application is not designed for automatically refreshing database. Application just load pre-downloaded dabase file, load it once on startup and used it. So you must care about refreshing databse by yourself by using for example crontab and included `db-update.sh` script. Example for crontab file:
+
+```sh
+0    2    1    *    *    root    /var/ip2location/db-update.sh "your token" "/var/ip2location/data/IP2LOCATION-LITE-DB3.BIN" > /dev/null 2>&1
+```
+
+Script takes two parameters, first - your database token from `ip2location.com`, and second - database file. In this example script will automatically refresh database every month at 2 AM, once at month. It's enough for free lite database version. Script will not damage database file on fail
+
+## Running docker container
+
+```sh
+docker run -d \
+    --network host \
+    --restart=always \
+    --name my-container-name \
+    -e ENV_DATA_DIR="/app/data" \
+    -e ENV_DEPLOYMENT="deployment" \
+    -e ENV_HOST="127.0.0.1" \
+    -e ENV_PORT="8080" \
+    -e ENV_WEB_URL="http://localhost:8080/" \
+    -v /etc/timezone:/etc/timezone:ro \
+    -v /var/ip2location/data:/app/data \
+    vladimirok5959/golang-ip2location:latest
+```

+ 0 - 0
bin/.keep


+ 0 - 0
build/.keep


+ 48 - 0
cmd/ip2location/main.go

@@ -0,0 +1,48 @@
+package main
+
+import (
+	"context"
+
+	"github.com/vladimirok5959/golang-ctrlc/ctrlc"
+	"github.com/vladimirok5959/golang-ip2location/internal/client"
+	"github.com/vladimirok5959/golang-ip2location/internal/consts"
+	"github.com/vladimirok5959/golang-ip2location/internal/server"
+	"github.com/vladimirok5959/golang-utils/utils/http/logger"
+	"github.com/vladimirok5959/golang-utils/utils/penv"
+)
+
+func init() {
+	if err := penv.ProcessConfig(&consts.Config); err != nil {
+		panic(err)
+	}
+
+	var err error
+	if consts.Config.DataDir == "" {
+		consts.Config.DataDir, err = consts.DataPath()
+		if err != nil {
+			panic(err)
+		}
+	}
+}
+
+func main() {
+	logger.AccessLogFile = consts.Config.AccessLogFile
+	logger.ErrorLogFile = consts.Config.ErrorLogFile
+
+	ctrlc.App(func(ctx context.Context, shutdown context.CancelFunc) *[]ctrlc.Iface {
+		cl, err := client.New(ctx, shutdown)
+		if err != nil {
+			return ctrlc.MakeError(shutdown, ctrlc.AppError(err))
+		}
+
+		sv, err := server.New(ctx, shutdown, cl)
+		if err != nil {
+			return ctrlc.MakeError(shutdown, ctrlc.AppError(err), cl)
+		}
+
+		return &[]ctrlc.Iface{
+			sv,
+			cl,
+		}
+	})
+}

+ 0 - 0
data/.keep


+ 52 - 0
db-update.sh

@@ -0,0 +1,52 @@
+#!/bin/bash
+
+TOKEN="$1"
+FILE="DB3LITEBIN"
+URL="https://www.ip2location.com/download/?token=${TOKEN}&file=${FILE}"
+
+FILE_ZIP_SOURCE="/tmp/db.zip"
+FILE_BIN_SOURCE="/tmp/IP2LOCATION-LITE-DB3.BIN"
+FILE_BIN_TARGET="$2"
+
+if [ "${TOKEN}" = "" ]; then
+	echo "Please, set token"
+	exit 1
+fi
+
+# Download
+echo "Download ip2location file..."
+curl -s -o "${FILE_ZIP_SOURCE}" "${URL}"
+
+# Check
+if [ ! -f "${FILE_ZIP_SOURCE}" ]; then
+	echo "ZIP file is not exists"
+	exit 1
+fi
+
+SIZE=$(stat --printf="%s" "${FILE_ZIP_SOURCE}")
+if [ ${SIZE} -lt 1024 ]; then
+	echo "ZIP file is small: ${SIZE}"
+	cat "${FILE_ZIP_SOURCE}"
+	echo "" && rm "${FILE_ZIP_SOURCE}"
+	exit 1
+fi
+
+# Unpack
+unzip -p "${FILE_ZIP_SOURCE}" "IP2LOCATION-LITE-DB3.BIN" > "${FILE_BIN_SOURCE}"
+rm "${FILE_ZIP_SOURCE}"
+
+# Check
+if [ ! -f "${FILE_BIN_SOURCE}" ]; then
+	echo "BIN file is not exists"
+	exit 1
+fi
+
+SIZE=$(stat --printf="%s" "${FILE_BIN_SOURCE}")
+if [ ${SIZE} -lt 1024 ]; then
+	echo "BIN file is small: ${SIZE}"
+	rm "${FILE_BIN_SOURCE}"
+	exit 1
+fi
+
+# Replace
+mv "${FILE_BIN_SOURCE}" "${FILE_BIN_TARGET}"

+ 23 - 0
go.mod

@@ -0,0 +1,23 @@
+module github.com/vladimirok5959/golang-ip2location
+
+go 1.19
+
+require (
+	github.com/ip2location/ip2location-go/v9 v9.4.1
+	github.com/onsi/ginkgo v1.16.5
+	github.com/onsi/gomega v1.19.0
+	github.com/vladimirok5959/golang-ctrlc v1.0.4
+	github.com/vladimirok5959/golang-utils v1.3.6
+)
+
+require (
+	github.com/fsnotify/fsnotify v1.4.9 // indirect
+	github.com/nxadm/tail v1.4.8 // indirect
+	github.com/rollbar/rollbar-go v1.4.4 // indirect
+	github.com/vladimirok5959/golang-server-sessions v1.0.9 // indirect
+	golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
+	golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
+	golang.org/x/text v0.3.7 // indirect
+	gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
+	gopkg.in/yaml.v2 v2.4.0 // indirect
+)

+ 103 - 0
go.sum

@@ -0,0 +1,103 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
+github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
+github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
+github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
+github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
+github.com/ip2location/ip2location-go/v9 v9.4.1 h1:Gf7KoyyIVnltwvd7TcwKrkJC9ZnYqiyndXEJtT07AyI=
+github.com/ip2location/ip2location-go/v9 v9.4.1/go.mod h1:s5SV6YZL10TpfPpXw//7fEJC65G/yH7Oh+Tjq9JcQEQ=
+github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
+github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
+github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
+github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
+github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
+github.com/onsi/ginkgo/v2 v2.1.3 h1:e/3Cwtogj0HA+25nMP1jCMDIf8RtRYbGwGGuBIFztkc=
+github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
+github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
+github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw=
+github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rollbar/rollbar-go v1.4.4 h1:XtkPvjEbGTYJA04eXyGabCXk3jL+sEZTlSdTLbzsHoI=
+github.com/rollbar/rollbar-go v1.4.4/go.mod h1:kLQ9gP3WCRGrvJmF0ueO3wK9xWocej8GRX98D8sa39w=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
+github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/vladimirok5959/golang-ctrlc v1.0.4 h1:paARfY0AsWqR/LDcRZ0CNfzIDW1LwKBNwsKwxtHoTS0=
+github.com/vladimirok5959/golang-ctrlc v1.0.4/go.mod h1:yX6w0Ke3YILU+g5h2v7Ww0PXj80/Y2ehGXYneQIDE+0=
+github.com/vladimirok5959/golang-server-sessions v1.0.9 h1:oGj3jfpIo5PtWojeGDexDtTmaaZtSY/vH2PcwZIqWNI=
+github.com/vladimirok5959/golang-server-sessions v1.0.9/go.mod h1:w0JRthleTg5D4lY32iczfuUfKCXpbgUiLXHhIUFyY4o=
+github.com/vladimirok5959/golang-utils v1.3.6 h1:PmS//Bd1qIFHNeEhzuQBRZgeOpMMFAzmjaB8WCVXjuI=
+github.com/vladimirok5959/golang-utils v1.3.6/go.mod h1:IwOGU0ErnuHJhSOvS3MuOJfbuI2G7VZY3EXRe44fD18=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
+golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 60 - 0
internal/client/client.go

@@ -0,0 +1,60 @@
+package client
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/ip2location/ip2location-go/v9"
+	"github.com/vladimirok5959/golang-ip2location/internal/consts"
+)
+
+type Client struct {
+	ctx  context.Context
+	base *ip2location.DB
+}
+
+type Result struct {
+	City         string
+	CountryLong  string
+	CountryShort string
+	Region       string
+}
+
+func New(ctx context.Context, shutdown context.CancelFunc) (*Client, error) {
+	f, err := consts.DataPathFile("IP2LOCATION-LITE-DB3.BIN")
+	if err != nil {
+		return nil, err
+	}
+
+	b, err := ip2location.OpenDB(f)
+	if err != nil {
+		return nil, err
+	}
+
+	c := Client{
+		ctx:  ctx,
+		base: b,
+	}
+
+	return &c, nil
+}
+
+func (c *Client) IP2Location(ctx context.Context, ip string) (*Result, error) {
+	if c.base == nil {
+		return nil, fmt.Errorf("database is not opened")
+	}
+
+	r, err := c.base.Get_all(ip)
+
+	return &Result{
+		City:         r.City,
+		CountryLong:  r.Country_long,
+		CountryShort: r.Country_short,
+		Region:       r.Region,
+	}, err
+}
+
+func (c *Client) Shutdown(ctx context.Context) error {
+	c.base.Close()
+	return nil
+}

+ 35 - 0
internal/consts/consts.go

@@ -0,0 +1,35 @@
+package consts
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+)
+
+const DataDirectory = "data"
+
+var Config struct {
+	AccessLogFile string `description:"Access log file"`
+	DataDir       string `description:"Application data directory"`
+	Deployment    string `default:"development" description:"Deployment type"`
+	ErrorLogFile  string `description:"Error log file"`
+	Host          string `default:"127.0.0.1" description:"Web server IP"`
+	Port          string `default:"8080" description:"Web server port"`
+	WebURL        string `default:"http://localhost:8080/" description:"Web server home URL"`
+}
+
+func DataPath() (string, error) {
+	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
+	if err != nil {
+		return dir, err
+	}
+	return strings.Join(append([]string{dir}, DataDirectory), string(os.PathSeparator)), nil
+}
+
+func DataPathFile(filename ...string) (string, error) {
+	dir, err := filepath.Abs(Config.DataDir)
+	if err != nil {
+		return dir, err
+	}
+	return strings.Join(append([]string{dir}, filename...), string(os.PathSeparator)), nil
+}

+ 1 - 0
internal/server/handler/api/api.go

@@ -0,0 +1 @@
+package api

+ 1 - 0
internal/server/handler/api/v1/v1.go

@@ -0,0 +1 @@
+package v1

+ 46 - 0
internal/server/handler/api/v1/v1_app_health/v1_app_health.go

@@ -0,0 +1,46 @@
+package v1_app_health
+
+import (
+	"net/http"
+
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
+	"github.com/vladimirok5959/golang-utils/utils/http/render"
+)
+
+type HealthColor int64
+
+const (
+	HealthColorGreen HealthColor = iota
+	HealthColorOrange
+	HealthColorRed
+)
+
+func (c HealthColor) String() string {
+	switch c {
+	case HealthColorGreen:
+		return "green"
+	case HealthColorOrange:
+		return "orange"
+	case HealthColorRed:
+		return "red"
+	}
+	return "unknown"
+}
+
+type Handler struct {
+	base.Handler
+}
+
+func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	colorHealth := HealthColorGreen
+
+	var resp struct {
+		Health string `json:"health"`
+	}
+
+	resp.Health = colorHealth.String()
+
+	if !render.JSON(w, r, resp) {
+		return
+	}
+}

+ 57 - 0
internal/server/handler/api/v1/v1_app_health/v1_app_health_test.go

@@ -0,0 +1,57 @@
+package v1_app_health_test
+
+import (
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/api/v1/v1_app_health"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
+)
+
+var _ = Describe("Server", func() {
+	Context("Endpoint", func() {
+		var srv *httptest.Server
+		var client *http.Client
+
+		AfterEach(func() {
+			srv.Close()
+		})
+
+		Context("/api/v1/app/health", func() {
+			apiEndpoint := "/api/v1/app/health"
+
+			BeforeEach(func() {
+				handler := v1_app_health.Handler{Handler: base.Handler{Client: nil, Shutdown: nil}}
+				srv = httptest.NewServer(handler)
+				client = srv.Client()
+			})
+
+			AfterEach(func() {
+				srv.Close()
+			})
+
+			It("respond with correct json", func() {
+				resp, err := client.Get(srv.URL + apiEndpoint)
+				Expect(err).To(Succeed())
+				defer resp.Body.Close()
+
+				Expect(resp.StatusCode).To(Equal(http.StatusOK))
+				Expect(resp.Header.Get("Content-Type")).To(Equal("application/json"))
+
+				body, err := io.ReadAll(resp.Body)
+				Expect(err).To(Succeed())
+
+				Expect(string(body)).To(MatchJSON(`{"health":"green"}`))
+			})
+		})
+	})
+})
+
+func TestSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "Server")
+}

+ 31 - 0
internal/server/handler/api/v1/v1_ip2location/v1_ip2location.go

@@ -0,0 +1,31 @@
+package v1_ip2location
+
+import (
+	"net/http"
+
+	"github.com/vladimirok5959/golang-ip2location/internal/client"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
+	"github.com/vladimirok5959/golang-utils/utils/http/apiserv"
+	"github.com/vladimirok5959/golang-utils/utils/http/helpers"
+	"github.com/vladimirok5959/golang-utils/utils/http/render"
+)
+
+type Handler struct {
+	base.Handler
+}
+
+func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	var res *client.Result
+	var err error
+
+	if h.Client != nil {
+		if res, err = h.Client.IP2Location(r.Context(), apiserv.GetParams(r)[1].String()); err != nil {
+			helpers.RespondAsBadRequest(w, r, err)
+			return
+		}
+	}
+
+	if !render.JSON(w, r, res) {
+		return
+	}
+}

+ 24 - 0
internal/server/handler/base/base.go

@@ -0,0 +1,24 @@
+package base
+
+import (
+	"context"
+	"html/template"
+	"net/http"
+
+	"github.com/vladimirok5959/golang-ip2location/internal/client"
+)
+
+type Handler struct {
+	Client   *client.Client
+	Shutdown context.CancelFunc
+}
+
+type ServerData struct {
+	Additional interface{}
+	URL        string
+	WebURL     string
+}
+
+func (h Handler) FuncMap(w http.ResponseWriter, r *http.Request) template.FuncMap {
+	return template.FuncMap{}
+}

+ 1 - 0
internal/server/handler/handler.go

@@ -0,0 +1 @@
+package handler

+ 45 - 0
internal/server/handler/page/page_index/page_index.go

@@ -0,0 +1,45 @@
+package page_index
+
+import (
+	"encoding/json"
+	"html/template"
+	"net/http"
+
+	"github.com/vladimirok5959/golang-ip2location/internal/consts"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/web"
+	"github.com/vladimirok5959/golang-utils/utils/http/helpers"
+	"github.com/vladimirok5959/golang-utils/utils/http/render"
+)
+
+type Handler struct {
+	base.Handler
+}
+
+func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	data := &base.ServerData{
+		URL:    r.URL.Path,
+		WebURL: consts.Config.WebURL,
+	}
+
+	var additional struct {
+		ClientIP  string
+		GeoIPData template.HTML
+	}
+
+	additional.ClientIP = helpers.ClientIP(r)
+
+	if h.Client != nil {
+		if res, err := h.Client.IP2Location(r.Context(), additional.ClientIP); err == nil {
+			if j, err := json.Marshal(res); err == nil {
+				additional.GeoIPData = template.HTML(string(j))
+			}
+		}
+	}
+
+	data.Additional = additional
+
+	if !render.HTML(w, r, h.FuncMap(w, r), data, web.IndexHtml, http.StatusOK) {
+		return
+	}
+}

+ 54 - 0
internal/server/server.go

@@ -0,0 +1,54 @@
+package server
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"github.com/vladimirok5959/golang-ip2location/internal/client"
+	"github.com/vladimirok5959/golang-ip2location/internal/consts"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/api/v1/v1_app_health"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/api/v1/v1_ip2location"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
+	"github.com/vladimirok5959/golang-ip2location/internal/server/handler/page/page_index"
+	"github.com/vladimirok5959/golang-utils/utils/http/apiserv"
+	"github.com/vladimirok5959/golang-utils/utils/http/helpers"
+)
+
+func NewMux(ctx context.Context, shutdown context.CancelFunc, client *client.Client) *apiserv.ServeMux {
+	mux := apiserv.NewServeMux()
+
+	handler := base.Handler{
+		Client:   client,
+		Shutdown: shutdown,
+	}
+
+	// Pages
+	mux.Get("/", page_index.Handler{Handler: handler})
+
+	// API
+	mux.Get("/api/v1/app/health", v1_app_health.Handler{Handler: handler})
+	mux.Get("/api/v1/app/status", helpers.HandleAppStatus())
+	mux.Get("/api/v1/ip2location/{s}", v1_ip2location.Handler{Handler: handler})
+
+	return mux
+}
+
+func New(ctx context.Context, shutdown context.CancelFunc, client *client.Client) (*http.Server, error) {
+	mux := NewMux(ctx, shutdown, client)
+	srv := &http.Server{
+		Addr:    consts.Config.Host + ":" + consts.Config.Port,
+		Handler: mux,
+	}
+	go func() {
+		fmt.Printf("Web server: http://%s:%s/\n", consts.Config.Host, consts.Config.Port)
+		if err := srv.ListenAndServe(); err != nil {
+			if err != http.ErrServerClosed {
+				fmt.Printf("Web server startup error: %s\n", err.Error())
+				shutdown()
+				return
+			}
+		}
+	}()
+	return srv, nil
+}

+ 69 - 0
internal/server/server_test.go

@@ -0,0 +1,69 @@
+package server_test
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+	"github.com/vladimirok5959/golang-ip2location/internal/server"
+)
+
+var _ = Describe("Server", func() {
+	Context("Endpoint", func() {
+		var ctx = context.Background()
+		var srv *httptest.Server
+		var client *http.Client
+
+		AfterEach(func() {
+			srv.Close()
+		})
+
+		Context("Routes", func() {
+			BeforeEach(func() {
+				mux := server.NewMux(ctx, nil, nil)
+				srv = httptest.NewServer(mux)
+				client = srv.Client()
+			})
+
+			AfterEach(func() {
+				srv.Close()
+			})
+
+			Context("Route", func() {
+				It("must exists", func() {
+					var routes = []string{
+						// Pages
+						"/",
+
+						// API
+						"/api/v1/app/health",
+						"/api/v1/app/status",
+						"/api/v1/ip2location/127.0.0.1",
+					}
+
+					for _, route := range routes {
+						resp, err := client.Get(srv.URL + route)
+						resp.Body.Close()
+						Expect(err).To(Succeed())
+						Expect(resp.StatusCode).NotTo(Equal(http.StatusNotFound))
+					}
+				})
+
+				It("must response with 404", func() {
+					resp, err := client.Get(srv.URL + "/qwertyuiopasdfghjklzxcvbnm")
+					resp.Body.Close()
+					Expect(err).To(Succeed())
+					Expect(resp.StatusCode).To(Equal(http.StatusNotFound))
+				})
+			})
+		})
+	})
+})
+
+func TestSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "Server")
+}

+ 17 - 0
internal/server/web/index.html

@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<meta charset="utf-8" />
+		<title>ip2location</title>
+		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
+		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
+		<style>html{min-height:100%;height:100%;position:relative}body{margin:0;padding:0;position:relative;width:100%;min-height:100%;height:100%;height:auto;display:table}.wrapper{padding:15px;text-align:center;display:table-cell;vertical-align:middle}h1,h2{font-weight:400;font-size:34px;line-height:36px;margin:10px 0}h2{font-weight:350;font-size:14px;line-height:18px;margin-bottom:0}@media only screen and (max-width:800px){.wrapper{padding:15px 0}h1,h2{padding:0 15px}}</style>
+	</head>
+	<body>
+		<div class="wrapper">
+			<h1>ip2location</h1>
+			<h2>{{$.Data.Additional.ClientIP}}</h2>
+			<h2>{{$.Data.Additional.GeoIPData}}</h2>
+		</div>
+	</body>
+</html>

+ 10 - 0
internal/server/web/web.go

@@ -0,0 +1,10 @@
+package web
+
+import (
+	_ "embed"
+)
+
+var (
+	//go:embed index.html
+	IndexHtml string
+)