First not working app skeleton with nix support and dependency setup and generated logo not final structure

This commit is contained in:
Jonas Hahn
2025-08-22 17:37:43 +02:00
parent 99306dd26f
commit 6f53cddf6c
24 changed files with 1382 additions and 87 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
qrank.db

27
Makefile Normal file
View File

@@ -0,0 +1,27 @@
######################
# Makefile for QRank #
######################
# Main target
run:
go run ./cmd
# Formatting the whole codebase
format:
gofmt -w ./src
gofmt -w ./cmd
# Test in verbose mode
test:
go test ./src -v
go test ./cmd -v
# Nix stuff
nix-run:
nix develop --command make run
nix-test:
nix develop --command make test
nix-format:
nix develop --command make format

View File

@@ -1,93 +1,9 @@
# QRank
The *easy* tracker for tabletop soccers with QR code integration.
Everything is still in development. Feel free to open issues and or pull requests.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.gwdg.de/qrank/qrank.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.gwdg.de/qrank/qrank/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
To run the application go to the root directory and run `make run` in the terminal. On a nix system it is possible to run with all dependencies via `make nix`. The listening address is `https://localhost:18765`.

BIN
assets/favicon.ico Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
assets/logo.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 753 KiB

9
cmd/main.go Normal file
View File

@@ -0,0 +1,9 @@
package main
import (
app "gitlab.gwdg.de/qrank/qrank/src"
)
func main() {
app.App()
}

8
cmd/main_test.go Normal file
View File

@@ -0,0 +1,8 @@
package main
import (
"testing"
)
// Dummy main function for testing
func TestMain(t *testing.T) {}

27
flake.lock generated Normal file
View File

@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1755704039,
"narHash": "sha256-gKlP0LbyJ3qX0KObfIWcp5nbuHSb5EHwIvU6UcNBg2A=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9cb344e96d5b6918e94e1bca2d9f3ea1e9615545",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-25.05",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

59
flake.nix Normal file
View File

@@ -0,0 +1,59 @@
{
description = "QRank Go (Gin + GORM) dev env with CGO (NixOS 25.05)";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
outputs = { self, nixpkgs }:
let
systems = [ "x86_64-linux" "aarch64-linux" ];
forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f (import nixpkgs { inherit system; }));
in
{
devShells = forAllSystems (pkgs:
let
# Pick the Go you want. pkgs.go is fine; change to pkgs.go_1_23 if you prefer a fixed version.
go = pkgs.go;
in {
default = pkgs.mkShell {
# Tools required for cgo and sqlite
buildInputs = [
go
pkgs.gcc
pkgs.pkg-config
pkgs.sqlite
];
# Optional (handy) tools
nativeBuildInputs = [
pkgs.git
];
# Enable CGO so mattn/go-sqlite3 works
CGO_ENABLED = 1;
# If you plan static linking, uncomment:
# hardeningDisable = [ "fortify" ];
shellHook = ''
echo "🔧 Nix dev shell ready (CGO_ENABLED=1)."
echo " Run: go run ."
'';
};
});
# Convenience runner: `nix run`
apps = forAllSystems (pkgs: {
default = {
type = "app";
program = pkgs.writeShellScriptBin "run-qrank" ''
set -euo pipefail
export CGO_ENABLED=1
exec ${pkgs.go}/bin/go run .
'' + "/bin/run-qrank";
};
});
# Optional: formatter for this repo
formatter = forAllSystems (pkgs: pkgs.nixpkgs-fmt);
};
}

44
go.mod Normal file
View File

@@ -0,0 +1,44 @@
module gitlab.gwdg.de/qrank/qrank
go 1.24.5
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.1 // 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.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.6.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/postgres v1.6.0 // indirect
gorm.io/driver/sqlite v1.6.0 // indirect
gorm.io/gorm v1.30.1 // indirect
)

101
go.sum Normal file
View File

@@ -0,0 +1,101 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.30.1 h1:lSHg33jJTBxs2mgJRfRZeLDG+WZaHYCk3Wtfl6Ngzo4=
gorm.io/gorm v1.30.1/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

134
src/app.go Normal file
View File

@@ -0,0 +1,134 @@
package src
// socqr-mvp: single-binary Go + Gin app with email-magic-link auth (debug links in logs),
// SQLite (switchable to Postgres), and four views: user view, enter scores, history, leaderboard.
//
// Quick start:
// go mod init socqr
// go get github.com/gin-gonic/gin gorm.io/gorm gorm.io/driver/sqlite gorm.io/driver/postgres
// go run .
//
// Env vars (optional):
// DATABASE_URL="postgres://user:pass@host:5432/dbname?sslmode=disable" // if set, uses Postgres; else SQLite file socqr.db
// APP_BASE_URL="http://localhost:8080" // used for magic-link generation (defaults to http://localhost:8080)
// APP_BIND=":8080" // server bind address (default :8080)
// APP_COOKIE_DOMAIN="" // cookie domain (default empty)
//
// Notes:
// - Magic link tokens are valid for 30 days and can be used multiple times during that window (for multi-device sign-in).
// - Session cookie is long-lived (~10 years). Delete cookie to sign out.
// - Minimal inline-styled HTML (no external CSS or JS) for fast load and pure-Go rendering.
// - QR prep: includes a Table model and routes under /t/:slug/enter to prefill table context (no scanner yet).
import (
"html/template"
"log"
"os"
"path/filepath"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// ===================== Globals =====================
var (
db *gorm.DB
baseURL string
cookieDomain string
)
const (
PORT = "18765"
)
// ===================== Templates =====================
var tpl *template.Template
func init() {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if filepath.Base(wd) == "src" {
wd = filepath.Join(wd, "..") // adjust if running from src dir
}
path := filepath.Join(wd, "templates", "*.html")
tpl = template.Must(template.New("").Funcs(template.FuncMap{
"fmtTime": func(t time.Time) string { return t.Local().Format("1000-01-01 10:10") },
}).ParseGlob(path))
}
// ===================== Main =====================
func App() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
baseURL = os.Getenv("APP_BASE_URL")
if baseURL == "" {
baseURL = "http://localhost:" + PORT
}
cookieDomain = os.Getenv("APP_COOKIE_DOMAIN")
// DB connect
var err error
dsn := os.Getenv("DATABASE_URL")
if dsn != "" {
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("postgres connect:", err)
}
log.Println("using Postgres")
} else {
db, err = gorm.Open(sqlite.Open("qrank.db"), &gorm.Config{})
if err != nil {
log.Fatal("sqlite connect:", err)
}
log.Println("using SQLite qrank.db")
}
if err := db.AutoMigrate(&User{}, &Session{}, &LoginToken{}, &Table{}, &Game{}, &GamePlayer{}); err != nil {
log.Fatal("migrate:", err)
}
r := gin.Default()
// Serve static files from the current directory
r.Static("/assets", "./assets")
// Routes
r.GET("/", getIndex)
r.GET("/login", getLogin)
r.POST("/login", postLogin)
r.GET("/magic", getMagic)
// Authenticated routes
r.GET("/enter", requireAuth(), getEnter)
r.POST("/enter", requireAuth(), postEnter)
// QR-prepped table routes
r.GET("/t/:tslug/enter", requireAuth(), getEnter)
r.POST("/t/:tslug/enter", requireAuth(), postEnter)
r.GET("/history", requireAuth(), getHistory)
r.GET("/leaderboard", requireAuth(), getLeaderboard)
r.GET("/u/:slug", requireAuth(), getUserView)
r.GET("/me", requireAuth(), getMe)
r.POST("/me", requireAuth(), postMe)
bind := os.Getenv("APP_BIND")
if bind == "" {
bind = ":" + PORT
}
log.Println("listening on", bind, "base:", baseURL)
if err := r.Run(bind); err != nil {
log.Fatal(err)
}
}

78
src/auth.go Normal file
View File

@@ -0,0 +1,78 @@
package src
import (
"database/sql"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func getSessionUser(c *gin.Context) *User {
cookie, err := c.Cookie("session")
if err != nil || cookie == "" {
return nil
}
var s Session
if err := db.Preload("User").Where("token = ?", cookie).First(&s).Error; err != nil {
return nil
}
return &s.User
}
func requireAuth() gin.HandlerFunc {
return func(c *gin.Context) {
if u := getSessionUser(c); u != nil {
c.Set("user", u)
c.Next()
return
}
c.Redirect(http.StatusFound, "/login")
c.Abort()
}
}
func setSessionCookie(c *gin.Context, token string) {
// Very long-lived cookie (~10 years)
maxAge := 10 * 365 * 24 * 60 * 60
httpOnly := true
secure := strings.HasPrefix(baseURL, "https://")
sameSite := http.SameSiteLaxMode
c.SetCookie("session", token, maxAge, "/", cookieDomain, secure, httpOnly)
// Workaround to set SameSite explicitly via header
c.Header("Set-Cookie", (&http.Cookie{Name: "session", Value: token, Path: "/", Domain: cookieDomain, MaxAge: maxAge, Secure: secure, HttpOnly: httpOnly, SameSite: sameSite}).String())
}
func findOrCreateUserByHandle(handle string) (*User, error) {
h := strings.TrimSpace(handle)
if h == "" {
return nil, sql.ErrNoRows
}
if strings.Contains(h, "@") { // email
if u, err := userByEmail(strings.ToLower(h)); err == nil {
return u, nil
}
// create
u := &User{Email: strings.ToLower(h), Username: defaultUsername()}
if err := ensureUniqueUsernameAndSlug(u); err != nil {
return nil, err
}
if err := db.Create(u).Error; err != nil {
return nil, err
}
return u, nil
}
// username
var u User
if err := db.Where("username = ?", h).First(&u).Error; err == nil {
return &u, nil
}
// If not found, create placeholder user with random email-like token
u = User{Email: mustRandToken(3) + "+placeholder@local", Username: h, Slug: slugify(h)}
if err := ensureUniqueUsernameAndSlug(&u); err != nil { /* best-effort */
}
if err := db.Create(&u).Error; err != nil {
return nil, err
}
return &u, nil
}

118
src/auth_test.go Normal file
View File

@@ -0,0 +1,118 @@
package src
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// setupTestDB initializes an in-memory SQLite DB for tests
func setupTestDB(t *testing.T) *gorm.DB {
t.Helper()
d, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
t.Fatalf("failed to open test db: %v", err)
}
if err := d.AutoMigrate(&User{}, &Session{}); err != nil {
t.Fatalf("failed to migrate test db: %v", err)
}
db = d // override global
return d
}
// TestFindOrCreateUserByHandle_Email
func TestFindOrCreateUserByHandle_Email(t *testing.T) {
setupTestDB(t)
u, err := findOrCreateUserByHandle("test@example.com")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if u.Email != "test@example.com" {
t.Errorf("expected email test@example.com, got %s", u.Email)
}
// Should return same user if called again
u2, err := findOrCreateUserByHandle("test@example.com")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if u.ID != u2.ID {
t.Errorf("expected same user ID, got %d and %d", u.ID, u2.ID)
}
}
// TestFindOrCreateUserByHandle_Username
func TestFindOrCreateUserByHandle_Username(t *testing.T) {
setupTestDB(t)
u, err := findOrCreateUserByHandle("PlayerOne")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(u.Email, "@local") {
t.Errorf("expected placeholder email, got %s", u.Email)
}
if u.Username != "PlayerOne" {
t.Errorf("expected username PlayerOne, got %s", u.Username)
}
}
// TestGetSessionUserAndRequireAuth
func TestGetSessionUserAndRequireAuth(t *testing.T) {
setupTestDB(t)
// Create a user + session
user := &User{Email: "auth@example.com", Username: "authuser"}
if err := db.Create(user).Error; err != nil {
t.Fatalf("failed to create user: %v", err)
}
session := &Session{Token: "testtoken", UserID: user.ID}
if err := db.Create(session).Error; err != nil {
t.Fatalf("failed to create session: %v", err)
}
// Make a Gin context with session cookie
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req, _ := http.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: "testtoken"})
c.Request = req
// Should find user
u := getSessionUser(c)
if u == nil || u.Email != "auth@example.com" {
t.Errorf("expected user auth@example.com, got %+v", u)
}
// Test requireAuth middleware with valid session
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
req, _ = http.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: "testtoken"})
c.Request = req
c.Next() // prepare pipeline
mw := requireAuth()
mw(c)
if c.IsAborted() {
t.Errorf("expected request to pass middleware, but it aborted")
}
// Test requireAuth middleware with no cookie
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
req, _ = http.NewRequest("GET", "/", nil)
c.Request = req
mw = requireAuth()
mw(c)
if !c.IsAborted() {
t.Errorf("expected request to abort when no session, but it passed")
}
}

348
src/handlers.go Normal file
View File

@@ -0,0 +1,348 @@
package src
import (
"errors"
"log"
"strings"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type ctxData map[string]any
func getIndex(c *gin.Context) {
if getSessionUser(c) != nil {
c.Redirect(302, "/enter")
return
}
getLogin(c)
}
func getLogin(c *gin.Context) {
render(c, "login", ctxData{})
}
func postLogin(c *gin.Context) {
email := strings.ToLower(strings.TrimSpace(c.PostForm("email")))
if email == "" {
c.Redirect(302, "/login")
return
}
// ensure user exists
var u User
tx := db.Where("email = ?", email).First(&u)
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
u = User{Email: email, Username: defaultUsername()}
if err := ensureUniqueUsernameAndSlug(&u); err != nil {
log.Println(err)
}
if err := db.Create(&u).Error; err != nil {
log.Println("create user:", err)
}
}
// create token valid 30 days
token := mustRandToken(24)
lt := LoginToken{Token: token, Email: email, ExpiresAt: now().Add(30 * 24 * time.Hour)}
if err := db.Create(&lt).Error; err != nil {
log.Println("create token:", err)
}
link := strings.TrimRight(baseURL, "/") + "/magic?token=" + token
log.Printf("[MAGIC LINK] %s for %s (valid until %s)\n", link, email, lt.ExpiresAt.Format(time.RFC3339))
render(c, "sent", ctxData{"Email": email})
}
func getMagic(c *gin.Context) {
token := c.Query("token")
if token == "" {
c.Redirect(302, "/login")
return
}
var lt LoginToken
if err := db.Where("token = ? AND expires_at > ?", token, now()).First(&lt).Error; err != nil {
c.String(400, "Invalid or expired token")
return
}
// find or create user by email again (in case)
u, err := userByEmail(lt.Email)
if err != nil {
c.String(500, "user lookup error")
return
}
// create session
sessTok := mustRandToken(24)
if err := db.Create(&Session{Token: sessTok, UserID: u.ID}).Error; err != nil {
c.String(500, "session error")
return
}
setSessionCookie(c, sessTok)
c.Redirect(302, "/enter")
}
func getEnter(c *gin.Context) {
var table *Table
if slug := c.Param("tslug"); slug != "" {
var t Table
if err := db.Where("slug = ?", slug).First(&t).Error; err == nil {
table = &t
}
}
post := "/enter"
if table != nil {
post = "/t/" + table.Slug + "/enter"
}
render(c, "enter", ctxData{"PostAction": post, "Table": table})
}
func postEnter(c *gin.Context) {
current := getSessionUser(c)
if current == nil {
c.Redirect(302, "/login")
return
}
a1h := c.PostForm("a1")
a2h := c.PostForm("a2")
b1h := c.PostForm("b1")
b2h := c.PostForm("b2")
scoreA := atoiSafe(c.PostForm("scoreA"))
scoreB := atoiSafe(c.PostForm("scoreB"))
// Resolve players (default A1 to current if empty)
if strings.TrimSpace(a1h) == "" {
a1h = current.Username
}
a1, _ := findOrCreateUserByHandle(a1h)
var a2, b1, b2 *User
if a2h != "" {
a2, _ = findOrCreateUserByHandle(a2h)
}
if b1h != "" {
b1, _ = findOrCreateUserByHandle(b1h)
}
if b2h != "" {
b2, _ = findOrCreateUserByHandle(b2h)
}
var tableID *uint
if slug := c.Param("tslug"); slug != "" {
var t Table
if err := db.Where("slug = ?", slug).First(&t).Error; err == nil {
tableID = &t.ID
}
}
g := Game{ScoreA: scoreA, ScoreB: scoreB, TableID: tableID}
if err := db.Create(&g).Error; err != nil {
c.String(500, "game create error")
return
}
players := []struct {
U *User
S string
}{{a1, "A"}}
if a2 != nil {
players = append(players, struct {
U *User
S string
}{a2, "A"})
}
if b1 != nil {
players = append(players, struct {
U *User
S string
}{b1, "B"})
}
if b2 != nil {
players = append(players, struct {
U *User
S string
}{b2, "B"})
}
for _, p := range players {
if p.U != nil {
db.Create(&GamePlayer{GameID: g.ID, UserID: p.U.ID, Side: p.S})
}
}
c.Redirect(302, "/history")
}
func getHistory(c *gin.Context) {
// Load recent games with players
var games []Game
db.Order("created_at desc").Limit(100).Preload("Table").Find(&games)
type GRow struct {
Game
PlayersA []User
PlayersB []User
}
var rows []GRow
for _, g := range games {
var gps []GamePlayer
db.Preload("User").Where("game_id = ?", g.ID).Find(&gps)
var a, b []User
for _, gp := range gps {
if gp.Side == "A" {
a = append(a, gp.User)
} else {
b = append(b, gp.User)
}
}
rows = append(rows, GRow{Game: g, PlayersA: a, PlayersB: b})
}
render(c, "history", ctxData{"Games": rows})
}
func getLeaderboard(c *gin.Context) {
// Simple metric: wins = games where player's side has higher score
type Row struct {
Username, Slug string
Wins, Games int
}
// Load last 1000 games for performance (simple MVP)
var games []Game
db.Order("created_at desc").Limit(1000).Find(&games)
// Build map of gameID->winnerSide
winner := map[uint]string{}
for _, g := range games {
side := ""
if g.ScoreA > g.ScoreB {
side = "A"
} else if g.ScoreB > g.ScoreA {
side = "B"
}
winner[g.ID] = side
}
// Count per user
type Cnt struct{ Wins, Games int }
counts := map[uint]*Cnt{}
users := map[uint]User{}
for _, g := range games {
var gps []GamePlayer
db.Preload("User").Where("game_id = ?", g.ID).Find(&gps)
for _, gp := range gps {
if counts[gp.UserID] == nil {
counts[gp.UserID] = &Cnt{}
users[gp.UserID] = gp.User
}
counts[gp.UserID].Games++
if winner[g.ID] != "" && winner[g.ID] == gp.Side {
counts[gp.UserID].Wins++
}
}
}
rows := []Row{}
for uid, cnt := range counts {
u := users[uid]
rows = append(rows, Row{Username: u.Username, Slug: u.Slug, Wins: cnt.Wins, Games: cnt.Games})
}
// Sort by wins desc, then games desc, then username
// Simple insertion sort to avoid extra imports
for i := 1; i < len(rows); i++ {
j := i
for j > 0 && (rows[j-1].Wins < rows[j].Wins || (rows[j-1].Wins == rows[j].Wins && (rows[j-1].Games < rows[j].Games || (rows[j-1].Games == rows[j].Games && rows[j-1].Username > rows[j].Username)))) {
rows[j-1], rows[j] = rows[j], rows[j-1]
j--
}
}
if len(rows) > 100 {
rows = rows[:100]
}
render(c, "leaderboard", ctxData{"Rows": rows})
}
func getUserView(c *gin.Context) {
slug := c.Param("slug")
u, err := userBySlug(slug)
if err != nil {
c.String(404, "user not found")
return
}
// Compute stats
type Stats struct{ Games, Wins, Losses int }
st := Stats{}
var gps []GamePlayer
db.Where("user_id = ?", u.ID).Find(&gps)
gameMap := map[uint]string{}
for _, gp := range gps {
gameMap[gp.GameID] = gp.Side
}
if len(gameMap) > 0 {
var games []Game
ids := make([]uint, 0, len(gameMap))
for gid := range gameMap {
ids = append(ids, gid)
}
db.Find(&games, ids)
for _, g := range games {
st.Games++
if g.ScoreA == g.ScoreB {
continue
}
if g.ScoreA > g.ScoreB && gameMap[g.ID] == "A" {
st.Wins++
} else if g.ScoreB > g.ScoreA && gameMap[g.ID] == "B" {
st.Wins++
} else {
st.Losses++
}
}
}
own := false
if cu := getSessionUser(c); cu != nil && cu.ID == u.ID {
own = true
}
render(c, "user", ctxData{"Viewed": u, "Stats": st, "Own": own})
}
func getMe(c *gin.Context) {
cu := getSessionUser(c)
if cu == nil {
c.Redirect(302, "/login")
return
}
render(c, "user", ctxData{"Viewed": cu, "Stats": struct{ Games, Wins, Losses int }{0, 0, 0}, "Own": true})
}
func postMe(c *gin.Context) {
cu := getSessionUser(c)
if cu == nil {
c.Redirect(302, "/login")
return
}
newU := strings.TrimSpace(c.PostForm("username"))
if newU == "" {
c.Redirect(302, "/me")
return
}
cu.Username = newU
cu.Slug = slugify(newU)
if err := ensureUniqueUsernameAndSlug(cu); err != nil {
log.Println("unique username error:", err)
}
if err := db.Save(cu).Error; err != nil {
log.Println("save user:", err)
}
c.Redirect(302, "/u/"+cu.Slug)
}

57
src/models.go Normal file
View File

@@ -0,0 +1,57 @@
package src
import (
"time"
)
type User struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
Email string `gorm:"uniqueIndex;size:320"`
Username string `gorm:"uniqueIndex;size:64"`
Slug string `gorm:"uniqueIndex;size:80"`
}
type Session struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
// No expiry by default; can add later
Token string `gorm:"uniqueIndex;size:128"`
UserID uint `gorm:"index"`
User User
}
type LoginToken struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
Token string `gorm:"uniqueIndex;size:128"`
Email string `gorm:"index;size:320"`
ExpiresAt time.Time `gorm:"index"`
}
type Table struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
Name string
Slug string `gorm:"uniqueIndex;size:80"`
}
type Game struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time `gorm:"index"`
TableID *uint `gorm:"index"`
Table *Table
ScoreA int
ScoreB int
}
type GamePlayer struct {
ID uint `gorm:"primaryKey"`
GameID uint `gorm:"index"`
UserID uint `gorm:"index"`
Side string `gorm:"size:1;index"` // "A" or "B"
User User
}

132
src/utils.go Normal file
View File

@@ -0,0 +1,132 @@
package src
import (
"crypto/rand"
"encoding/hex"
"errors"
"log"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func mustRandToken(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return hex.EncodeToString(b)
}
func now() time.Time { return time.Now().UTC() }
func defaultUsername() string {
// io-game style: adjective-animal-xxxx
adjectives := []string{"swift", "brave", "mighty", "cheeky", "sneaky", "zippy", "bouncy", "crispy", "fuzzy", "spicy", "snappy", "jazzy", "spry", "bold", "witty"}
animals := []string{"otter", "panda", "falcon", "lynx", "badger", "tiger", "koala", "yak", "gecko", "eagle", "mamba", "fox", "yak", "whale", "rhino"}
a := adjectives[int(time.Now().UnixNano())%len(adjectives)]
an := animals[int(time.Now().UnixNano()/17)%len(animals)]
return a + "-" + an + "-" + strings.ToLower(mustRandToken(2))
}
func slugify(s string) string {
s = strings.ToLower(s)
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, " ", "-")
// keep alnum and - only
var b strings.Builder
for _, r := range s {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' {
b.WriteRune(r)
}
}
out := b.String()
if out == "" {
out = "user-" + mustRandToken(2)
}
return out
}
func ensureUniqueUsernameAndSlug(u *User) error {
// try to keep username/slug unique by appending short token if needed
baseU := u.Username
baseS := slugify(u.Username)
for i := 0; i < 5; i++ {
candU := baseU
candS := baseS
if i > 0 {
suffix := "-" + mustRandToken(1)
candU = baseU + suffix
candS = baseS + suffix
}
var cnt int64
db.Model(&User{}).Where("username = ?", candU).Count(&cnt)
if cnt == 0 {
db.Model(&User{}).Where("slug = ?", candS).Count(&cnt)
if cnt == 0 {
u.Username = candU
u.Slug = candS
return nil
}
}
}
return errors.New("cannot create unique username/slug")
}
func userByEmail(email string) (*User, error) {
var u User
tx := db.Where("email = ?", strings.ToLower(email)).First(&u)
if tx.Error != nil {
return nil, tx.Error
}
return &u, nil
}
func userBySlug(slug string) (*User, error) {
var u User
tx := db.Where("slug = ?", slug).First(&u)
if tx.Error != nil {
return nil, tx.Error
}
return &u, nil
}
func atoiSafe(s string) int {
var n int
for _, r := range s {
if r < '0' || r > '9' {
return 0
}
}
_, _ = fmtSscanf(s, "%d", &n)
return n
}
// minimal sscanf to avoid fmt import just for one call
func fmtSscanf(s, format string, a *int) (int, error) {
// Only supports "%d"
n := 0
for i := 0; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
break
}
n = n*10 + int(c-'0')
}
*a = n
return 1, nil
}
func render(c *gin.Context, name string, data ctxData) {
u := getSessionUser(c)
if data == nil {
data = ctxData{}
}
log.Println("tpl error:", name)
data["CurrentUser"] = u
if err := tpl.ExecuteTemplate(c.Writer, name, data); err != nil {
log.Println("tpl error:", err)
c.Status(500)
}
}

130
templates/base.html Normal file
View File

@@ -0,0 +1,130 @@
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{block "title" .}}QRank{{end}}</title>
<link rel="icon" type="image/png" href="/assets/favicon.ico">
<link rel="apple-touch-icon" href="/assets/favicon.ico">
<link rel="shortcut icon" href="/assets/favicon.ico">
<style>
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, "Helvetica Neue", Arial, sans-serif;
margin: 0;
padding: 0;
background: #f7f7f9;
color: #111
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 16px
}
.card {
background: #fff;
border-radius: 12px;
padding: 16px;
margin: 12px 0;
box-shadow: 0 2px 6px rgba(0, 0, 0, .06)
}
.row {
display: flex;
gap: 8px;
flex-wrap: wrap
}
.btn {
display: inline-block;
padding: 10px 14px;
border-radius: 10px;
border: 1px solid #ddd;
background: #fafafa;
text-decoration: none
}
.btn-primary {
background: #111;
color: #fff;
border-color: #111
}
.input {
width: 100%;
padding: 10px;
border-radius: 10px;
border: 1px solid #ddd
}
.label {
font-size: 12px;
color: #444;
margin-bottom: 6px;
display: block
}
.header {
padding: 12px 16px;
background: #fff;
position: sticky;
top: 0;
border-bottom: 1px solid #eee
}
.nav a {
margin-right: 12px;
text-decoration: none;
color: #111
}
.small {
font-size: 12px;
color: #666
}
.list li {
padding: 8px 0;
border-bottom: 1px solid #f0f0f0
}
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
background: #eee;
font-size: 12px
}
</style>
</head>
<body>
<div class="header">
<div class="container">
<div class="row" style="justify-content:space-between;align-items:center">
<div><strong><a href="/" style="text-decoration:none;color:#111">QRank</a></strong></div>
<div class="nav">
<a href="/enter">Enter scores</a>
<a href="/history">History</a>
<a href="/leaderboard">Leaderboard</a>
{{if .CurrentUser}}
<a href="/me">@{{.CurrentUser.Username}}</a>
{{else}}
<a href="/login">Log in</a>
{{end}}
</div>
</div>
</div>
</div>
<div class="container">
{{block "content" .}}{{end}}
</div>
</body>
</html>
{{end}}

31
templates/enter.html Normal file
View File

@@ -0,0 +1,31 @@
{{define "enter"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>Enter a game</h2>
{{if .Table}}<p class="small">Table: <span class="badge">{{.Table.Name}}</span></p>{{end}}
<form method="POST" action="{{.PostAction}}">
<div class="row">
<div style="flex:1;min-width:280px">
<h3>Team A</h3>
<label class="label">Player A1</label>
<input class="input" name="a1" value="{{.CurrentUser.Username}}">
<label class="label">Player A2 (optional)</label>
<input class="input" name="a2" placeholder="username or email">
<label class="label">Score A</label>
<input class="input" type="number" name="scoreA" value="10" min="0" required>
</div>
<div style="flex:1;min-width:280px">
<h3>Team B</h3>
<label class="label">Player B1</label>
<input class="input" name="b1" placeholder="username or email">
<label class="label">Player B2 (optional)</label>
<input class="input" name="b2" placeholder="username or email">
<label class="label">Score B</label>
<input class="input" type="number" name="scoreB" value="8" min="0" required>
</div>
</div>
<div style="height:12px"></div>
<button class="btn btn-primary" type="submit">Submit result</button>
</form>
</div>
{{end}}

22
templates/history.html Normal file
View File

@@ -0,0 +1,22 @@
{{define "history"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>Global history</h2>
<ul class="list">
{{range .Games}}
<li>
<div class="small">{{fmtTime .CreatedAt}}</div>
<div>
{{if .Table}}<span class="badge">{{.Table.Name}}</span> {{end}}
Team A {{.ScoreA}} \u2013 {{.ScoreB}} Team B
</div>
<div class="small">
{{range .PlayersA}}@{{.Username}} {{end}}vs {{range .PlayersB}}@{{.Username}} {{end}}
</div>
</li>
{{else}}
<li class="small">No games yet. Be the first!</li>
{{end}}
</ul>
</div>
{{end}}

View File

@@ -0,0 +1,13 @@
{{define "leaderboard"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>Leaderboard (by wins)</h2>
<ol>
{{range .Rows}}
<li>@<a href="/u/{{.Slug}}">{{.Username}}</a> \u2014 {{.Wins}} wins ({{.Games}} games)</li>
{{else}}
<li class="small">No players yet.</li>
{{end}}
</ol>
</div>
{{end}}

13
templates/login.html Normal file
View File

@@ -0,0 +1,13 @@
{{define "login"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>Sign in with your email</h2>
<p class="small">No password needed. We'll send you a magic link (for now it prints in the server logs).</p>
<form method="POST" action="/login">
<label class="label">Email</label>
<input class="input" type="email" name="email" placeholder="you@example.com" required>
<div style="height:8px"></div>
<button class="btn btn-primary" type="submit">Send magic link</button>
</form>
</div>
{{end}}

9
templates/sent.html Normal file
View File

@@ -0,0 +1,9 @@
{{define "sent"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>Check the server logs</h2>
<p class="small">We just printed a magic link for <strong>{{.Email}}</strong>. Open it here to sign in.
Token expires in 30 days.</p>
<a class="btn" href="/login">Back</a>
</div>
{{end}}

18
templates/user.html Normal file
View File

@@ -0,0 +1,18 @@
{{define "user"}}{{template "base" .}}{{end}}
{{define "content"}}
<div class="card">
<h2>@{{.Viewed.Username}}</h2>
<p class="small">Joined {{fmtTime .Viewed.CreatedAt}}</p>
<p>Games played: {{.Stats.Games}} Wins: {{.Stats.Wins}} Losses: {{.Stats.Losses}}</p>
{{if .Own}}
<hr>
<h3>Update your profile</h3>
<form method="POST" action="/me">
<label class="label">Username</label>
<input class="input" name="username" value="{{.Viewed.Username}}" required>
<div style="height:8px"></div>
<button class="btn btn-primary">Save</button>
</form>
{{end}}
</div>
{{end}}