Merge pull request #14 from mcstatus-io/v3

Merge v3 into main
This commit is contained in:
Jacob 2024-07-18 14:05:26 -05:00 committed by GitHub
commit 184c93459f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 490 additions and 107 deletions

View File

@ -1,6 +1,7 @@
environment: development
host: 0.0.0.0
port: 3001
mongodb: ${MONGO_URL} # Use an environment variable to define the Redis URL
redis: ${REDIS_URL} # Use an environment variable to define the Redis URL
cache:
enable_locks: true

22
go.mod
View File

@ -6,9 +6,10 @@ toolchain go1.22.3
require (
github.com/go-redsync/redsync/v4 v4.13.0
github.com/gofiber/fiber/v2 v2.52.4
github.com/mcstatus-io/mcutil/v3 v3.6.0
github.com/redis/go-redis/v9 v9.5.1
github.com/gofiber/fiber/v2 v2.52.5
github.com/mcstatus-io/mcutil/v4 v4.0.0-20240718180705-427b3bcbde17
github.com/redis/go-redis/v9 v9.5.4
go.mongodb.org/mongo-driver v1.16.0
gopkg.in/yaml.v3 v3.0.1
)
@ -16,16 +17,25 @@ require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.53.0 // indirect
github.com/valyala/fasthttp v1.55.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.20.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240424034433-3c2c7870ae76 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
)

74
go.sum
View File

@ -6,6 +6,8 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
@ -16,10 +18,14 @@ github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-redsync/redsync/v4 v4.13.0 h1:49X6GJfnbLGaIpBBREM/zA4uIMDXKAh1NDkvQ1EkZKA=
github.com/go-redsync/redsync/v4 v4.13.0/go.mod h1:HMW4Q224GZQz6x1Xc7040Yfgacukdzu7ifTDAKiyErQ=
github.com/gofiber/fiber/v2 v2.52.4 h1:P+T+4iK7VaqUsq2PALYEfBBo6bJZ4q3FP8cZ84EggTM=
github.com/gofiber/fiber/v2 v2.52.4/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=
github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws=
github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@ -27,8 +33,8 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
@ -36,10 +42,12 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mcstatus-io/mcutil/v3 v3.6.0 h1:IJqIXMtVtz1yUcMKxnrUIcAlChm/OTNAPzyb16TTwLk=
github.com/mcstatus-io/mcutil/v3 v3.6.0/go.mod h1:6Rv4qnejaTezu/feuQ2M4131phQxw0Q4C5h3An/iNxI=
github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8=
github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/mcstatus-io/mcutil/v4 v4.0.0-20240718180705-427b3bcbde17 h1:gdlFoHcepuGydv0yE29hrpdxIarTm0Z+8taA4QMndNw=
github.com/mcstatus-io/mcutil/v4 v4.0.0-20240718180705-427b3bcbde17/go.mod h1:yC91WInI1U2GAMFWgpPgsAULPVS2o+4JCZbiiWhHwxM=
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/redis/go-redis/v9 v9.5.4 h1:vOFYDKKVgrI5u++QvnMT7DksSMYg7Aw/Np4vLJLKLwY=
github.com/redis/go-redis/v9 v9.5.4/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/redis/rueidis v1.0.19 h1:s65oWtotzlIFN8eMPhyYwxlwLR1lUdhza2KtWprKYSo=
github.com/redis/rueidis v1.0.19/go.mod h1:8B+r5wdnjwK3lTFml5VtxjzGOQAC+5UmujoD12pDrEo=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@ -49,16 +57,54 @@ github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08Yu
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.53.0 h1:lW/+SUkOxCx2vlIu0iaImv4JLrVRnbbkpCoaawvA4zc=
github.com/valyala/fasthttp v1.53.0/go.mod h1:6dt4/8olwq9QARP/TDuPmWyWcl4byhpvTJ4AAtcz+QM=
github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8=
github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRVfcxxoHiOM=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20240424034433-3c2c7870ae76 h1:tBiBTKHnIjovYoLX/TPkcf+OjqqKGQrPtGT3Foz+Pgo=
github.com/youmark/pkcs8 v0.0.0-20240424034433-3c2c7870ae76/go.mod h1:SQliXeA7Dhkt//vS29v3zpbEwoa+zb2Cn5xj5uO4K5U=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver v1.16.0 h1:tpRsfBJMROVHKpdGyc1BBEzzjDUWjItxbVSZ8Ls4BQ4=
go.mongodb.org/mongo-driver v1.16.0/go.mod h1:oB6AhJQvFQL4LEHyXi6aJzQJtBiTQHiAd83l0GdFaiw=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
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/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
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/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@ -15,6 +15,7 @@ var (
Environment: "production",
Host: "127.0.0.1",
Port: 3001,
MongoDB: nil,
Redis: nil,
Cache: ConfigCache{
EnableLocks: true,
@ -22,7 +23,6 @@ var (
BedrockStatusDuration: time.Minute,
IconDuration: time.Minute * 15,
},
AccessControl: ConfigAccessControl{},
}
)
@ -31,9 +31,9 @@ type Config struct {
Environment string `yaml:"environment"`
Host string `yaml:"host"`
Port uint16 `yaml:"port"`
MongoDB *string `yaml:"mongodb"`
Redis *string `yaml:"redis"`
Cache ConfigCache `yaml:"cache"`
AccessControl ConfigAccessControl `yaml:"access_control"`
}
// ConfigCache represents the caching durations of various responses.
@ -44,12 +44,6 @@ type ConfigCache struct {
IconDuration time.Duration `yaml:"icon_duration"`
}
// ConfigAccessControl is the configuration for the CORS headers
type ConfigAccessControl struct {
Enable bool `yaml:"enable"`
AllowedOrigins []string `yaml:"allowed_origins"`
}
// ReadFile reads the configuration from the given file and overrides values using environment variables.
func (c *Config) ReadFile(file string) error {
data, err := os.ReadFile(file)
@ -99,5 +93,9 @@ func (c *Config) overrideWithEnvVars() error {
c.Redis = &value
}
if value := os.Getenv("MONGO_URL"); value != "" {
c.MongoDB = &value
}
return nil
}

View File

@ -26,6 +26,7 @@ var (
},
})
r *Redis = &Redis{}
db *MongoDB = &MongoDB{}
config *Config = DefaultConfig
instanceID uint16 = 0
)
@ -51,6 +52,14 @@ func init() {
log.Println("Successfully retrieved EULA blocked servers")
if config.MongoDB != nil {
if err = db.Connect(); err != nil {
log.Fatalf("Failed to connect to MongoDB: %v", err)
}
log.Println("Successfully connected to MongoDB")
}
if config.Redis != nil {
if err = r.Connect(); err != nil {
log.Fatalf("Failed to connect to Redis: %v", err)
@ -72,6 +81,7 @@ func init() {
func main() {
defer r.Close()
defer db.Close()
if err := app.Listen(fmt.Sprintf("%s:%d", config.Host, config.Port+instanceID)); err != nil {
panic(err)

198
src/mongo.go Normal file
View File

@ -0,0 +1,198 @@
package main
import (
"context"
"errors"
"net/url"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
CollectionApplications string = "applications"
CollectionTokens string = "tokens"
CollectionRequestLog string = "request_log"
ErrMongoNotConnected error = errors.New("cannot use method as MongoDB is not connected")
)
type MongoDB struct {
Client *mongo.Client
Database *mongo.Database
}
type Application struct {
ID string `bson:"_id" json:"id"`
Name string `bson:"name" json:"name"`
ShortDescription string `bson:"shortDescription" json:"shortDescription"`
User string `bson:"user" json:"user"`
Token string `bson:"token" json:"token"`
RequestCount uint64 `bson:"requestCount" json:"requestCount"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
}
type Token struct {
ID string `bson:"_id" json:"id"`
Name string `bson:"name" json:"name"`
Token string `bson:"token" json:"token"`
RequestCount uint64 `bson:"requestCount" json:"requestCount"`
Application string `bson:"application" json:"application"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
LastUsedAt time.Time `bson:"lastUsedAt" json:"lastUsedAt"`
}
func (c *MongoDB) Connect() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
parsedURI, err := url.Parse(*config.MongoDB)
if err != nil {
return err
}
client, err := mongo.Connect(ctx, options.Client().ApplyURI(*config.MongoDB))
if err != nil {
return err
}
c.Client = client
c.Database = client.Database(strings.TrimPrefix(parsedURI.Path, "/"))
return nil
}
func (c *MongoDB) GetTokenByToken(token string) (*Token, error) {
if c.Client == nil {
return nil, ErrMongoNotConnected
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
cur := c.Database.Collection(CollectionTokens).FindOne(ctx, bson.M{"token": token})
if err := cur.Err(); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, nil
}
return nil, err
}
var result Token
if err := cur.Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
func (c *MongoDB) GetApplicationByID(id string) (*Application, error) {
if c.Client == nil {
return nil, ErrMongoNotConnected
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
cur := c.Database.Collection(CollectionApplications).FindOne(ctx, bson.M{"_id": id})
if err := cur.Err(); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, nil
}
return nil, err
}
var result Application
if err := cur.Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
func (c *MongoDB) UpdateToken(id string, update bson.M) error {
if c.Client == nil {
return ErrMongoNotConnected
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, err := c.Database.Collection(CollectionTokens).UpdateOne(
ctx,
bson.M{"_id": id},
update,
)
return err
}
func (c *MongoDB) IncrementApplicationRequestCount(id string) error {
if c.Client == nil {
return ErrMongoNotConnected
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, err := c.Database.Collection(CollectionApplications).UpdateOne(
ctx,
bson.M{"_id": id},
bson.M{
"$inc": bson.M{
"totalRequests": 1,
},
},
)
return err
}
func (c *MongoDB) UpsertRequestLog(query, update bson.M) error {
if c.Client == nil {
return ErrMongoNotConnected
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, err := c.Database.Collection(CollectionRequestLog).UpdateOne(
ctx,
query,
update,
&options.UpdateOptions{
Upsert: PointerOf(true),
},
)
return err
}
func (c *MongoDB) Close() error {
if c.Client == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return c.Client.Disconnect(ctx)
}

View File

@ -13,8 +13,9 @@ import (
"github.com/gofiber/fiber/v2/middleware/favicon"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/mcstatus-io/mcutil/v3"
"github.com/mcstatus-io/mcutil/v3/options"
"github.com/mcstatus-io/mcutil/v4/options"
"github.com/mcstatus-io/mcutil/v4/util"
"github.com/mcstatus-io/mcutil/v4/vote"
)
func init() {
@ -26,15 +27,13 @@ func init() {
Data: assets.Favicon,
}))
if config.AccessControl.Enable {
if config.Environment == "development" {
app.Use(cors.New(cors.Config{
AllowOrigins: strings.Join(config.AccessControl.AllowedOrigins, ","),
AllowOrigins: "*",
AllowMethods: "HEAD,OPTIONS,GET,POST",
ExposeHeaders: "X-Cache-Hit,X-Cache-Time-Remaining",
}))
}
if config.Environment == "development" {
app.Use(logger.New(logger.Config{
Format: "${time} ${ip}:${port} -> ${status}: ${method} ${path} (${latency})\n",
TimeFormat: "2006/01/02 15:04:05",
@ -56,23 +55,31 @@ func PingHandler(ctx *fiber.Ctx) error {
// JavaStatusHandler returns the status of the Java edition Minecraft server specified in the address parameter.
func JavaStatusHandler(ctx *fiber.Ctx) error {
address := strings.ToLower(ctx.Params("address"))
opts, err := GetStatusOptions(ctx)
if err != nil {
return err
}
host, port, err := ParseAddress(ctx.Params("address"), 25565)
if err != nil {
if _, _, err := util.ParseAddress(address); err != nil {
return ctx.Status(http.StatusBadRequest).SendString("Invalid address value")
}
if err = r.Increment(fmt.Sprintf("java-hits:%s-%d", host, port)); err != nil {
authorized, err := Authenticate(ctx)
// This check should work for both scenarios, because nil should be returned if the user
// is unauthorized, and err will be nil in that case.
if err != nil || !authorized {
return err
}
response, expiresAt, err := GetJavaStatus(host, port, opts)
if err = r.Increment(fmt.Sprintf("java-hits:%s", address)); err != nil {
return err
}
response, expiresAt, err := GetJavaStatus(address, opts)
if err != nil {
return err
@ -89,23 +96,23 @@ func JavaStatusHandler(ctx *fiber.Ctx) error {
// BedrockStatusHandler returns the status of the Bedrock edition Minecraft server specified in the address parameter.
func BedrockStatusHandler(ctx *fiber.Ctx) error {
address := strings.ToLower(ctx.Params("address"))
opts, err := GetStatusOptions(ctx)
if err != nil {
return err
}
host, port, err := ParseAddress(ctx.Params("address"), 19132)
if err != nil {
if _, _, err := util.ParseAddress(address); err != nil {
return ctx.Status(http.StatusBadRequest).SendString("Invalid address value")
}
if err = r.Increment(fmt.Sprintf("bedrock-hits:%s-%d", host, port)); err != nil {
if err = r.Increment(fmt.Sprintf("bedrock-hits:%s", address)); err != nil {
return err
}
response, expiresAt, err := GetBedrockStatus(host, port, opts)
response, expiresAt, err := GetBedrockStatus(address, opts)
if err != nil {
return err
@ -122,19 +129,19 @@ func BedrockStatusHandler(ctx *fiber.Ctx) error {
// IconHandler returns the server icon for the specified Java edition Minecraft server.
func IconHandler(ctx *fiber.Ctx) error {
address := strings.ToLower(ctx.Params("address"))
opts, err := GetStatusOptions(ctx)
if err != nil {
return err
}
host, port, err := ParseAddress(ctx.Params("address"), 25565)
if err != nil {
if _, _, err := util.ParseAddress(address); err != nil {
return ctx.Status(http.StatusBadRequest).SendString("Invalid address value")
}
icon, expiresAt, err := GetServerIcon(host, port, opts)
icon, expiresAt, err := GetServerIcon(address, opts)
if err != nil {
return err
@ -166,9 +173,9 @@ func SendVoteHandler(ctx *fiber.Ctx) error {
defer cancel()
if err = mcutil.SendVote(c, opts.Host, opts.Port, options.Vote{
Token: opts.Token,
if err = vote.SendVote(c, opts.Host, opts.Port, options.Vote{
PublicKey: opts.PublicKey,
Token: opts.Token,
ServiceName: opts.ServiceName,
Username: opts.Username,
IPAddress: opts.IPAddress,

View File

@ -12,10 +12,12 @@ import (
"sync"
"time"
"github.com/mcstatus-io/mcutil/v3"
"github.com/mcstatus-io/mcutil/v3/formatting"
"github.com/mcstatus-io/mcutil/v3/options"
"github.com/mcstatus-io/mcutil/v3/response"
"github.com/mcstatus-io/mcutil/v4/formatting"
"github.com/mcstatus-io/mcutil/v4/options"
"github.com/mcstatus-io/mcutil/v4/query"
"github.com/mcstatus-io/mcutil/v4/response"
"github.com/mcstatus-io/mcutil/v4/status"
"github.com/mcstatus-io/mcutil/v4/util"
)
// BaseStatus is the base response properties for returning any status response from the API.
@ -124,8 +126,8 @@ type SRVRecord struct {
}
// GetJavaStatus returns the status response of a Java Edition server, either using cache or fetching a fresh status.
func GetJavaStatus(host string, port uint16, opts *StatusOptions) (*JavaStatusResponse, time.Duration, error) {
cacheKey := GetCacheKey(host, port, opts)
func GetJavaStatus(host string, opts *StatusOptions) (*JavaStatusResponse, time.Duration, error) {
cacheKey := GetCacheKey(host, opts)
// Wait for any other processes to finish fetching the status of this server
if config.Cache.EnableLocks {
@ -154,7 +156,11 @@ func GetJavaStatus(host string, port uint16, opts *StatusOptions) (*JavaStatusRe
// Fetch a fresh status from the server itself
{
response := FetchJavaStatus(host, port, opts)
response, err := FetchJavaStatus(host, opts)
if err != nil {
return nil, 0, err
}
data, err := json.Marshal(response)
@ -166,13 +172,13 @@ func GetJavaStatus(host string, port uint16, opts *StatusOptions) (*JavaStatusRe
return nil, 0, err
}
return &response, 0, nil
return response, 0, nil
}
}
// GetBedrockStatus returns the status response of a Bedrock Edition server, either using cache or fetching a fresh status.
func GetBedrockStatus(host string, port uint16, opts *StatusOptions) (*BedrockStatusResponse, time.Duration, error) {
cacheKey := GetCacheKey(host, port, nil)
func GetBedrockStatus(host string, opts *StatusOptions) (*BedrockStatusResponse, time.Duration, error) {
cacheKey := GetCacheKey(host, nil)
// Wait for any other processes to finish fetching the status of this server
if config.Cache.EnableLocks {
@ -201,7 +207,11 @@ func GetBedrockStatus(host string, port uint16, opts *StatusOptions) (*BedrockSt
// Fetch a fresh status from the server itself
{
response := FetchBedrockStatus(host, port, opts)
response, err := FetchBedrockStatus(host, opts)
if err != nil {
return nil, 0, err
}
data, err := json.Marshal(response)
@ -213,13 +223,13 @@ func GetBedrockStatus(host string, port uint16, opts *StatusOptions) (*BedrockSt
return nil, 0, err
}
return &response, 0, nil
return response, 0, nil
}
}
// GetServerIcon returns the icon image of a Java Edition server, either using cache or fetching a fresh image.
func GetServerIcon(host string, port uint16, opts *StatusOptions) ([]byte, time.Duration, error) {
cacheKey := GetCacheKey(host, port, nil)
func GetServerIcon(host string, opts *StatusOptions) ([]byte, time.Duration, error) {
cacheKey := GetCacheKey(host, nil)
// Fetch the cached icon if it exists
{
@ -244,7 +254,7 @@ func GetServerIcon(host string, port uint16, opts *StatusOptions) ([]byte, time.
defer cancel()
status, err := mcutil.Status(ctx, host, port)
status, err := status.Modern(ctx, host)
if err == nil && status.Favicon != nil && strings.HasPrefix(*status.Favicon, "data:image/png;base64,") {
data, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(*status.Favicon, "data:image/png;base64,"))
@ -268,15 +278,15 @@ func GetServerIcon(host string, port uint16, opts *StatusOptions) ([]byte, time.
}
// FetchJavaStatus fetches fresh information about a Java Edition Minecraft server.
func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusResponse {
func FetchJavaStatus(host string, opts *StatusOptions) (*JavaStatusResponse, error) {
var (
err error
srvRecord *net.SRV
resolvedHost string = host
ipAddress *string
statusResult *response.JavaStatus
legacyStatusResult *response.JavaStatusLegacy
queryResult *response.FullQuery
statusResult *response.StatusModern
legacyStatusResult *response.StatusLegacy
queryResult *response.QueryFull
wg sync.WaitGroup
)
@ -291,7 +301,7 @@ func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusRe
// Lookup the SRV record
{
srvRecord, err = mcutil.LookupSRV("tcp", host)
srvRecord, err = util.LookupSRV(host)
if err == nil && srvRecord != nil {
resolvedHost = strings.Trim(srvRecord.Target, ".")
@ -318,7 +328,7 @@ func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusRe
// Retrieve the post-netty rewrite Java Edition status (Minecraft 1.8+)
{
go func() {
statusResult, _ = mcutil.Status(statusContext, host, port, options.JavaStatus{
statusResult, _ = status.Modern(statusContext, host, options.StatusModern{
EnableSRV: true,
Timeout: opts.Timeout - time.Millisecond*100,
ProtocolVersion: 47,
@ -342,7 +352,7 @@ func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusRe
// Retrieve the pre-netty rewrite Java Edition status (Minecraft 1.7 and below)
{
go func() {
legacyStatusResult, _ = mcutil.StatusLegacy(legacyContext, host, port, options.JavaStatusLegacy{
legacyStatusResult, _ = status.Legacy(legacyContext, host, options.StatusLegacy{
EnableSRV: true,
Timeout: opts.Timeout - time.Millisecond*100,
ProtocolVersion: 47,
@ -361,7 +371,7 @@ func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusRe
// Retrieve the query information (if it is available)
if opts.Query {
go func() {
queryResult, _ = mcutil.FullQuery(queryContext, host, port, options.Query{
queryResult, _ = query.Full(queryContext, host, options.Query{
Timeout: opts.Timeout - time.Millisecond*100,
})
@ -371,14 +381,14 @@ func FetchJavaStatus(host string, port uint16, opts *StatusOptions) JavaStatusRe
wg.Wait()
return BuildJavaResponse(host, port, statusResult, legacyStatusResult, queryResult, srvRecord, ipAddress)
return BuildJavaResponse(host, statusResult, legacyStatusResult, queryResult, srvRecord, ipAddress)
}
// FetchBedrockStatus fetches a fresh status of a Bedrock Edition server.
func FetchBedrockStatus(host string, port uint16, opts *StatusOptions) BedrockStatusResponse {
func FetchBedrockStatus(host string, opts *StatusOptions) (*BedrockStatusResponse, error) {
var (
ipAddress *string
status *response.BedrockStatus
result *response.StatusBedrock
)
// Resolve the connection hostname to an IP address
@ -396,19 +406,29 @@ func FetchBedrockStatus(host string, port uint16, opts *StatusOptions) BedrockSt
defer cancel()
status, _ = mcutil.StatusBedrock(ctx, host, port)
result, _ = status.Bedrock(ctx, host)
}
return BuildBedrockResponse(host, port, status, ipAddress)
return BuildBedrockResponse(host, result, ipAddress)
}
// BuildJavaResponse builds the response data from the status and query information.
func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, legacyStatus *response.JavaStatusLegacy, query *response.FullQuery, srvRecord *net.SRV, ipAddress *string) (result JavaStatusResponse) {
result = JavaStatusResponse{
func BuildJavaResponse(host string, status *response.StatusModern, legacyStatus *response.StatusLegacy, query *response.QueryFull, srvRecord *net.SRV, ipAddress *string) (result *JavaStatusResponse, err error) {
hostname, port, err := util.ParseAddress(host)
if err != nil {
return nil, err
}
if port == nil {
port = PointerOf(uint16(util.DefaultJavaPort))
}
result = &JavaStatusResponse{
BaseStatus: BaseStatus{
Online: false,
Host: host,
Port: port,
Host: hostname,
Port: *port,
IPAddress: ipAddress,
EULABlocked: IsBlockedAddress(host),
RetrievedAt: time.Now().UnixMilli(),
@ -423,9 +443,9 @@ func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, le
result.JavaStatus = &JavaStatus{
Version: &JavaVersion{
NameRaw: status.Version.NameRaw,
NameClean: status.Version.NameClean,
NameHTML: status.Version.NameHTML,
NameRaw: status.Version.Name.Raw,
NameClean: status.Version.Name.Clean,
NameHTML: status.Version.Name.HTML,
Protocol: status.Version.Protocol,
},
Players: JavaPlayers{
@ -447,9 +467,9 @@ func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, le
for _, player := range status.Players.Sample {
result.Players.List = append(result.Players.List, Player{
UUID: player.ID,
NameRaw: player.NameRaw,
NameClean: player.NameClean,
NameHTML: player.NameHTML,
NameRaw: player.Name.Raw,
NameClean: player.Name.Clean,
NameHTML: player.Name.HTML,
})
}
}
@ -458,8 +478,8 @@ func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, le
result.Icon = status.Favicon
}
if status.ModInfo != nil {
for _, mod := range status.ModInfo.Mods {
if status.Mods != nil {
for _, mod := range status.Mods.List {
result.Mods = append(result.Mods, Mod{
Name: mod.ID,
Version: mod.Version,
@ -488,9 +508,9 @@ func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, le
if legacyStatus.Version != nil {
result.Version = &JavaVersion{
NameRaw: legacyStatus.Version.NameRaw,
NameClean: legacyStatus.Version.NameClean,
NameHTML: legacyStatus.Version.NameHTML,
NameRaw: legacyStatus.Version.Name.Raw,
NameClean: legacyStatus.Version.Name.Clean,
NameHTML: legacyStatus.Version.Name.HTML,
Protocol: legacyStatus.Version.Protocol,
}
}
@ -600,12 +620,22 @@ func BuildJavaResponse(host string, port uint16, status *response.JavaStatus, le
}
// BuildBedrockResponse builds the response data from the status information.
func BuildBedrockResponse(host string, port uint16, status *response.BedrockStatus, ipAddress *string) (result BedrockStatusResponse) {
result = BedrockStatusResponse{
func BuildBedrockResponse(host string, status *response.StatusBedrock, ipAddress *string) (result *BedrockStatusResponse, err error) {
hostname, port, err := util.ParseAddress(host)
if err != nil {
return nil, err
}
if port == nil {
port = PointerOf(uint16(util.DefaultBedrockPort))
}
result = &BedrockStatusResponse{
BaseStatus: BaseStatus{
Online: false,
Host: host,
Port: port,
Host: hostname,
Port: *port,
IPAddress: ipAddress,
EULABlocked: IsBlockedAddress(host),
RetrievedAt: time.Now().UnixMilli(),

View File

@ -1,6 +1,7 @@
package main
import (
"crypto/rand"
"crypto/sha1"
_ "embed"
"encoding/hex"
@ -19,6 +20,7 @@ import (
"time"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/bson"
)
var (
@ -235,6 +237,7 @@ func GetVoteOptions(ctx *fiber.Ctx) (*VoteOptions, error) {
return &result, nil
}
// GetStatusOptions returns the options for status routes, with the default values filled in.
func GetStatusOptions(ctx *fiber.Ctx) (*StatusOptions, error) {
result := &StatusOptions{}
@ -267,10 +270,9 @@ func GetInstanceID() (uint16, error) {
}
// GetCacheKey generates a unique key used for caching status results in Redis.
func GetCacheKey(host string, port uint16, opts *StatusOptions) string {
func GetCacheKey(host string, opts *StatusOptions) string {
values := &url.Values{}
values.Set("host", host)
values.Set("port", strconv.FormatUint(uint64(port), 10))
if opts != nil {
values.Set("query", strconv.FormatBool(opts.Query))
@ -279,6 +281,71 @@ func GetCacheKey(host string, port uint16, opts *StatusOptions) string {
return SHA256(values.Encode())
}
// Authenticate checks and requires authentication for the current request, by finding the token.
func Authenticate(ctx *fiber.Ctx) (bool, error) {
if config.MongoDB == nil {
return true, nil
}
authToken := ctx.Get("Authorization")
if len(authToken) < 1 {
if err := ctx.Status(http.StatusUnauthorized).SendString("Missing 'Authorization' header in request"); err != nil {
return false, err
}
return false, nil
}
token, err := db.GetTokenByToken(authToken)
if err != nil {
return false, err
}
if token == nil {
if err := ctx.Status(http.StatusUnauthorized).SendString("Invalid or expired authorization token, please generate another one in the dashboard"); err != nil {
return false, err
}
return false, nil
}
if err = db.IncrementApplicationRequestCount(token.Application); err != nil {
return false, err
}
if err = db.UpdateToken(
token.ID,
bson.M{
"$inc": bson.M{"requestCount": 1},
"$set": bson.M{"lastUsedAt": time.Now().UTC()},
},
); err != nil {
return false, err
}
if err = db.UpsertRequestLog(
bson.M{
"application": token.Application,
"timestamp": GetStartOfHour(),
"token": token.ID,
},
bson.M{
"$setOnInsert": bson.M{
"_id": RandomHexString(16),
},
"$inc": bson.M{
"requestCount": 1,
},
},
); err != nil {
return false, err
}
return true, nil
}
// SHA256 returns the result of hashing the input value using SHA256 algorithm.
func SHA256(input string) string {
result := sha1.Sum([]byte(input))
@ -312,3 +379,19 @@ func Map[I, O any](arr []I, f func(I) O) []O {
return result
}
// GetStartOfHour returns the current date and time rounded down to the start of the hour.
func GetStartOfHour() time.Time {
return time.Now().UTC().Truncate(time.Hour)
}
// RandomHexString returns a random hexadecimal string with the specified byte length.
func RandomHexString(byteLength int) string {
data := make([]byte, byteLength)
if _, err := rand.Read(data); err != nil {
panic(err)
}
return hex.EncodeToString(data)
}