Skip to content

About

A Go service providing APIs and everyday development utilities.

Topics

Resources

Stars

10 stars

Watchers

0 watching

Forks

Repository files navigation

go-gin-gee

Gee is a project that provides several services for everyday work. The project is based on Gin [1], and follows the ProjectLayout [3] structure. In addition, some daily scripts in the folder scripts, which can be used by the command run directly.

Table of Contents

Script Examples

1. Change Git name and email for different projects.

macOS Bash or zsh:

bash scripts/bash/batch-set-git-identity.sh --path="/Users/X/Web" --username="<your-name>" --useremail="<your-email>"

Windows 10 Git Bash:

bash scripts/bash/batch-set-git-identity.sh --path="C:/Web" --username="<your-name>" --useremail="<your-email>"

Usage: English | 简体中文

2. git pull all projects in a folder.

go run scripts/batch-git-pull/main.go -path="/Users/X/Web"

Usage: English | 简体中文

3. Consolidate designated files/folders and execute customized ESLint commands.

go run scripts/eslint-files/main.go -files="file1.js,file2.js" -esConf="custom.eslintrc.js" -esCom="--fix"

Usage: English | 简体中文

More in folder scripts.

API Examples

The base URL for this API is an environment variate ${BASE_URL}, such as https://example.com/path.

Key-Value Store

The key-value API exposes exactly three JSON endpoints:

Method Path Authorization Behavior
POST /api/gee/kv/get Required only for private entries Read an entry using a key from the JSON body
POST /api/gee/kv/set X-API-Key required Create or replace an entry (upsert)
POST /api/gee/kv/increment X-API-Key required Atomically increment a numeric counter

Configure accepted keys in Data.KVAPIKeys. Keys must match ^[a-z0-9][a-z0-9._:-]{0,127}$; they are never read from paths, query strings, or headers. Entry visibility is public or private and defaults to private. An unauthorized read of a private entry returns the same 404 response as an unknown key.

All responses contain exactly code, message, and data. Application codes complement, rather than replace, meaningful HTTP statuses:

Code Message HTTP status
0 success 200 or 201
40001 invalid request 400
40002 invalid key 400
40003 invalid value 400
40101 API key required 401
40301 access denied 403
40401 key not found 404
40901 incompatible value type 409
50001 internal server error 500

Get a public value:

curl --request POST '${BASE_URL}/api/gee/kv/get' \
  --header 'Content-Type: application/json' \
  --data '{"key":"site.title"}'
{
  "code": 0,
  "message": "success",
  "data": {
    "key": "site.title",
    "value": "Gee Service",
    "content_type": "text/plain",
    "visibility": "public",
    "created_at": "2026-07-26T03:00:00Z",
    "updated_at": "2026-07-26T03:00:00Z"
  }
}

Create or replace a value:

curl --request POST '${BASE_URL}/api/gee/kv/set' \
  --header 'Content-Type: application/json' \
  --header "X-API-Key: ${GEE_KV_API_KEY}" \
  --data '{"key":"site.title","value":"Gee Service","content_type":"text/plain","visibility":"private"}'

Creation returns HTTP 201; replacement returns HTTP 200. The response data includes created: true or created: false.

{
  "code": 0,
  "message": "success",
  "data": {
    "key": "site.title",
    "value": "Gee Service",
    "content_type": "text/plain",
    "visibility": "private",
    "created": true
  }
}

Increment a counter:

curl --request POST '${BASE_URL}/api/gee/kv/increment' \
  --header 'Content-Type: application/json' \
  --header "X-API-Key: ${GEE_KV_API_KEY}" \
  --data '{"key":"page.views","delta":1}'

An omitted delta defaults to 1; explicit zero, positive, and negative deltas are supported. Missing counters start at zero, and increments use database-side arithmetic. A key already used for a non-counter entry returns HTTP 409.

{
  "code": 0,
  "message": "success",
  "data": {
    "key": "page.views",
    "value": 101,
    "delta": 1
  }
}

Errors contain no internal details and normally use data: null:

{
  "code": 40401,
  "message": "key not found",
  "data": null
}

Generate Short Link

Description:

Generate the short link for the original link.

Path: /api/gee/generate-short-link

Method: POST

Params:

Params Type Description Required
ori_link string Exact original destination Yes
base_url string Short-link base URL; defaults to Data.BaseURL No
one_time boolean Consume the link at resolution; defaults to false No
common_api_key string Creation credential for a permanent direct link No

Example:

curl --location --request POST '${BASE_URL}/api/gee/generate-short-link' \
--header 'Content-Type: application/json' \
--data-raw '{
  "ori_link": "http://blog.mazey.net/tiny?ts=654321-221467-f22c24-493220-228e97-d90c73"
}'

Returns:

Params Type Description Required
data string Generated short-link URL Yes
tiny_link string Deprecated alias of data Yes
errors array Empty array on success Yes

Use data for the generated URL. tiny_link is deprecated and contains the identical value.

Example:

Success: Status Code 201

{
  "tiny_link": "${BASE_URL}/t/b",
  "data": "${BASE_URL}/t/b",
  "errors": []
}

Failure: Status Code 400

{
  "code": 400
}

Look up the original URL with GET /api/gee/query-short-link?link_key=b. The query accepts only link_key, not tiny_key, and returns {"ori_link":"<original URL>"}. Open /t/b to resolve the link. Creation requests with a valid JSON common_api_key from Data.CommonAPIKeys create permanent direct links usable by anyone. Missing, empty, and invalid keys create links that first open the Redirect warning page. The server derives this policy; a body field such as direct_redirect cannot override it. Opening headers and later API-key removal do not change an existing link's policy. Manually configured SpecialLinks are trusted and always redirect directly. Resolution checks configuration first, using the first matching key, then falls back to the database. Configured aliases work before their database records exist.

The database deduplicates a fixed JSON representation of the exact original URL, effective base URL, one_time, and the authorized redirect policy using SHA-256. Different policies receive different short keys. An omitted override and an explicit override equal to Data.BaseURL reuse the same record. Reuse never resets visits; regenerating a consumed one-time link returns the expired link. URLs are not normalized.

One-time consumption happens at resolution, including before the warning page is shown. It retains asynchronous visit counting and does not guarantee exclusion of simultaneous visits. The query API also resolves links and remains public; the warning is not destination access control.

Go reads the warning URL only from Data.LinkRedirectPageURL, configured as https://i.mazey.net/pages/redirect/ in the maintained examples and Webmazey application configuration. Incoming warning-URL headers are ignored. Go encodes the complete destination as the url query parameter, preserving other configured query parameters. Missing or invalid configuration returns 503 for warning-required links, never a direct fallback. Direct links and trusted SpecialLinks do not need warning configuration. Redirect responses use Cache-Control: no-store. Deploy the warning page and its external assets before enabling the backend behavior; publishing is a separate operation.

This link schema targets a new database; no legacy link-data migration is provided. The model stores original_url, dedup_hash, and direct_redirect, with unique fingerprint and short-key indexes. Creation allocates the numeric ID and final key inside one transaction. If its ID-derived key matches SpecialLinks, creation converts that new candidate into the configured direct, reusable link, then retries the original request with a fresh ID. A loop handles consecutive collisions without an arbitrary retry limit or underscore suffix. Failure rolls back all records from the request. For example, with a and b reserved, a fresh database stores those special links at IDs 1 and 2, then returns /t/c for the ordinary request at ID 3. Aliases such as m and dl consume no IDs until generation reaches them.

Use Data.SpecialLinks for fixed department aliases such as /t/ui:

{
  "SpecialLinks": [
    { "Key": "ui", "Link": "https://ui.example.com/" }
  ]
}

Keys are matched case-sensitively. Configure distinct keys and valid HTTP(S) destinations. There is no startup provisioning or snapshot verification. Special records created on collision use fixed:<key> as their internal identity, allowing multiple aliases to share a destination without ordinary URL deduplication merging them. Existing ordinary records are never converted during deduplication.

Each new deployment uses a fresh SQLite database. Configuration is the durable source of fixed aliases; ordinary generated links do not survive replacement of that database. Configuration changes take effect after restart and override stored destinations. Removing an alias can reveal its previously stored destination; adding an alias can shadow a generated link. The application does not reset databases, migrate legacy link data, or synchronize stored special records with later configuration changes.

Data.CommonAPIKeys defaults to an empty list and is independent of Webhook and KV keys. Send the optional common_api_key string in the creation JSON body. The X-Common-API-Key header does not authorize direct links. Keys are never persisted, logged, returned, or included in the fingerprint. Keep keys in trusted clients, not public frontend bundles or generated URLs, and avoid request-body logging in callers and infrastructure. For Webmazey, keep Data.EnableCORS set to off: Go handles OPTIONS, while the existing Nginx configuration owns CORS. JSON requests still require cross-origin preflight support for Content-Type; no Nginx policy change is required by this field. Standalone Go can set Data.EnableCORS to on. Neither setting changes the warning URL.

Retired APIs

GET /api/gee/get-tag-name is retired. The route remains available only to return HTTP 410 Gone with Cache-Control: no-store:

{
  "code": 41001,
  "message": "This API has been retired.",
  "data": null
}

The endpoint no longer calls Docker Hub or returns tagName. Clients should stop using it.

To retire another API, register its existing HTTP method and path directly with controllers.RetiredAPI and remove its unused implementation. The shared handler uses the existing response envelope and CodeAPIRetired; unknown routes retain their normal behavior.

Build

Default:

go build cmd/api/main.go

Linux:

It's usually helpful to run the command chmod u+x script-name-linux-amd64 if the permission error happens.

GOOS=linux GOARCH=amd64 go build -o dist/api-linux-amd64 cmd/api/main.go

macOS:

GOOS=darwin GOARCH=amd64 go build -o dist/api-mac-darwin-amd64 cmd/api/main.go

Windows:

GOOS=windows GOARCH=amd64 go build -o dist/api-windows-amd64 cmd/api/main.go

Deployment

Environment Variables:

  • ${BASE_URL}: The only application configuration environment override. A nonempty value overrides Data.BaseURL; an empty or absent value preserves the JSON setting.

Configuration files use JSON. Select the file with --config-path, which defaults to data/config.json. All other settings come from JSON or application defaults.

Discord and private webhook API configuration:

  • Data.WebhookID: Discord webhook ID.
  • Data.WebhookToken: Discord webhook token.
  • Data.EnableWebhookAPI: Set to on to enable POST /api/gee/webhook-message.
  • Data.WebhookAPIKeys: API keys accepted by the private webhook API via X-Webhook-API-Key.

Key-value API configuration:

  • Data.KVAPIKeys: API keys accepted by key-value write operations and private reads via X-API-Key.

Common feature configuration:

  • Data.CommonAPIKeys: Config-file API keys accepted through the JSON common_api_key field when creating direct short links. Defaults to []; future features must opt in explicitly.

API-key checks apply only where handlers explicitly implement them. The webhook endpoint uses its webhook-specific header and key list; the key-value endpoints use X-API-Key and Data.KVAPIKeys.

Upgrading does not automatically drop legacy user tables. After backing up the database and verifying the deployment, operators may optionally remove obsolete tables such as gee_user and gee_user_role manually.

Supervisor

[program:api]
directory=/web/go-gin-gee
command=/web/go-gin-gee/dist/api-linux-amd64 --config-path="/web/go-gin-gee/data/config.json"
autostart=true
autorestart=true
environment=BASE_URL="https://example.com/path"

Docker

Quick Start

GEE_VERSION="v$(date +"%Y%m%d%H%M%S")" && \
GEE_TAG="go-gin-gee:${GEE_VERSION}" && \
docker build -t "${GEE_TAG}" . && \
docker run --name "go-gin-gee-${GEE_VERSION}" -p 3000:3000 "${GEE_TAG}"

Build Image

Run bash ./scripts/bash/docker-build.sh -h to see the help message.

Usage: docker-build.sh [OPTIONS] [ENV_VARS...]
Build and run a Docker container for the go-gin-gee API.

Options:
  -r, --run     Run the Docker container after building (default)
  -b, --build   Build the Docker image but do not run it
  -h, --help    Print this help message and exit

Environment variables:
  Any additional arguments passed to the script will be passed as environment variables to the Docker container.

Usage:

${RUN_FLAG} is optional and defaults to -r (run). ${BASE_URL} optionally overrides Data.BaseURL. Short-link creation requires either a configured base URL or a request-provided base_url. Configure Discord credentials in the JSON file.

bash ./scripts/bash/docker-build.sh ${RUN_FLAG} \
  "BASE_URL=${BASE_URL}"

Examples:

Example 1: Build and Push

bash ./scripts/bash/docker-build.sh -b

Example 2: Build and Run

bash ./scripts/bash/docker-build.sh -r \
  "BASE_URL=https://example.com/path"

Run Container

Run bash ./scripts/bash/docker-run.sh -h to see the help message.

Usage: docker-run.sh [OPTIONS] IMAGE_TAG [ENV_VARS...]
Run a Docker container from the specified IMAGE_TAG with the specified environment variables.

Options:
  -h, --help    Print this help message and exit

Environment variables:
  Any additional arguments passed to the script will be passed as environment variables to the Docker container.

Note:
  The first argument (IMAGE_TAG) must be the tag name of the Docker image to run.

Find the latest image tag name: Tags

Usage:

bash ./scripts/bash/docker-run.sh "${DOCKER_HUB_REPOSITORY_TAGNAME}" \
  "BASE_URL=${BASE_URL}"

Example:

bash ./scripts/bash/docker-run.sh "docker.io/mazeyqian/go-gin-gee:v20230615221222-api" \
  "BASE_URL=https://example.com/path"

Documentation

Download swag:

go install github.com/swaggo/swag/cmd/swag@v1.16.6

Generate:

swag init --dir cmd/api,internal/api/controllers --parseDependency --output docs

Make sure your GO Path is on the PATH environment variable export PATH=$(go env GOPATH)/bin:$PATH if the following error occurs command not found: swag.

Run and visit: http://localhost:3000/docs/index.html

Contributing

Local Development Setup

Use Go 1.25 or later and a C compiler for SQLite's CGO driver. The selected Go 1.25 validation toolchain is 1.25.13. See the dependency maintenance guide for upgrade and validation requirements.

git clone https://github.com/chengchuu/go-gin-gee.git
cd go-gin-gee
go mod download
go run scripts/init/main.go && \
go run cmd/api/main.go --config-path="data/config.json"

Details

Download Project:

git clone https://github.com/chengchuu/go-gin-gee.git
cd go-gin-gee

Download modules:

go mod download

If i/o timeout, run the command to replace the proxy:

go env -w GOPROXY=https://goproxy.cn

To disable the proxy completely and download modules directly:

go env -w GOPROXY=direct

To reset to Go default proxy settings:

go env -w GOPROXY=https://proxy.golang.org,direct

It's necessary to run the command go run scripts/init/main.go when serving the project first.

Initialization copies assets/data/config.json to data/config.json. The shared example uses release mode. For Gin debug mode, set Server.Mode to debug in your local data/config.json.

Serve:

go run cmd/api/main.go --config-path="data/config.json"

Visit: http://127.0.0.1:3000/api/ping.

pong/v1.0.0/2022-09-29 04:52:43

References

  1. Gin Web Framework
  2. lo - Iterate over slices, maps, channels...
  3. Standard Go Project Layout
  4. script
  5. go-rest-template

About

A Go service providing APIs and everyday development utilities.

Topics

Resources

Stars

10 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages