first version

This commit is contained in:
mi6e4ka 2024-03-26 19:04:00 +03:00
parent 209534e8d5
commit 53a1aa2cc5
Signed by: mi6e4ka
GPG Key ID: 2070C80A0E25C7F8
12 changed files with 512 additions and 25 deletions

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
.env

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.env

16
Dockerfile Normal file
View File

@ -0,0 +1,16 @@
FROM golang:1.22-alpine as build
WORKDIR /app
COPY . .
ENV GOCACHE=/root/.cache/go-build
RUN --mount=type=cache,target="/root/.cache/go-build" go build .
RUN --mount=type=cache,target="/root/.cache/go-build" go build -C cert .
FROM nginx:alpine-slim
COPY --from=build app app
WORKDIR /app
COPY nginx.conf /etc/nginx/nginx.conf
ENTRYPOINT [ "sh", "entrypoint.sh" ]

5
README.md Normal file
View File

@ -0,0 +1,5 @@
# how to run
`docker run -p 443:443 -p 80:80 --name gitea-pages -v gitea-pages-ssl:/etc/ssl -d gitea-pages`
## gen ssl (first run)
`docker exec -it gp /app/cert/cert root.domain`
and restart docker container!

130
cert/cert.go Normal file
View File

@ -0,0 +1,130 @@
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"log"
"os"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
)
// You'll need a user or account type that implements acme.User
type MyUser struct {
Email string
Registration *registration.Resource
key crypto.PrivateKey
}
func (u *MyUser) GetEmail() string {
return u.Email
}
func (u MyUser) GetRegistration() *registration.Resource {
return u.Registration
}
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
return u.key
}
type DNSProviderBestDNS struct {
apiAuthToken string
}
func NewDNSProviderBestDNS(apiAuthToken string) (*DNSProviderBestDNS, error) {
return &DNSProviderBestDNS{apiAuthToken: apiAuthToken}, nil
}
func (d *DNSProviderBestDNS) Present(domain, token, keyAuth string) error {
info := dns01.GetChallengeInfo(domain, keyAuth)
fmt.Println()
fmt.Println("------")
fmt.Println()
fmt.Println("Please create DNS TXT record, for domain", info.FQDN, "with these content:")
fmt.Println()
fmt.Println(info.Value)
fmt.Println()
fmt.Println("------")
fmt.Scanln()
// make API request to set a TXT record on fqdn with value and TTL
return nil
}
func (d *DNSProviderBestDNS) CleanUp(domain, token, keyAuth string) error {
// clean up any state you created in Present, like removing the TXT record
fmt.Println("------")
fmt.Println()
fmt.Println("you can delete the TXT record, and press enter to continue")
fmt.Println()
fmt.Println("------")
fmt.Scanln()
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: ./cert root.domain")
os.Exit(1)
}
fmt.Println("root domain is", os.Args[1])
// Create a user. New accounts need an email and private key to start.
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Fatal(err)
}
var email string
fmt.Print("enter you email > ")
fmt.Scanln(&email)
myUser := MyUser{
Email: email,
key: privateKey,
}
config := lego.NewConfig(&myUser)
//config.CADirURL = lego.LEDirectoryStaging
config.Certificate.KeyType = certcrypto.RSA2048
// A client facilitates communication with the CA server.
client, err := lego.NewClient(config)
if err != nil {
log.Fatal(err)
}
bestDNS, err := NewDNSProviderBestDNS("my-auth-token")
if err != nil {
log.Fatal(err)
}
err = client.Challenge.SetDNS01Provider(bestDNS)
if err != nil {
log.Fatal(err)
}
// New users will need to register
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
log.Fatal(err)
}
myUser.Registration = reg
request := certificate.ObtainRequest{
Domains: []string{os.Args[1], "*." + os.Args[1]},
Bundle: true,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
log.Fatal(err)
}
// Each certificate comes back with the cert bytes, the bytes of the client's
// private key, and a certificate URL. SAVE THESE TO DISK.
os.Mkdir("/etc/ssl", 0777)
os.WriteFile("/etc/ssl/cert.crt", certificates.Certificate, 0777)
os.WriteFile("/etc/ssl/priv.key", certificates.PrivateKey, 0777)
// ... all done.
}

8
entrypoint.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/bash
if [ -e /etc/ssl/cert.crt ] && [ -e /etc/ssl/priv.key ]
then
nginx & GIN_MODE=release ./giteapages
else
echo "create certs first"
tail -f /dev/null
fi

23
go.mod
View File

@ -2,13 +2,19 @@ module mi6e4ka/giteapages
go 1.22.0
require github.com/gin-gonic/gin v1.9.1
require (
github.com/gin-gonic/gin v1.9.1
github.com/go-acme/lego/v4 v4.16.1
github.com/joho/godotenv v1.5.1
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-jose/go-jose/v4 v4.0.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.14.0 // indirect
@ -16,17 +22,20 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/miekg/dns v1.1.58 // 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.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.17.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

47
go.sum
View File

@ -1,6 +1,8 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
@ -13,6 +15,10 @@ 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.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-acme/lego/v4 v4.16.1 h1:JxZ93s4KG0jL27rZ30UsIgxap6VGzKuREsSkkyzeoCQ=
github.com/go-acme/lego/v4 v4.16.1/go.mod h1:AVvwdPned/IWpD/ihHhMsKnveF7HHYAz/CmtXi7OZoE=
github.com/go-jose/go-jose/v4 v4.0.1 h1:QVEPDE3OluqXBQZDcnNvQrInro2h0e4eqNbnZSWqS6U=
github.com/go-jose/go-jose/v4 v4.0.1/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@ -24,9 +30,12 @@ github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QX
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/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
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=
@ -34,8 +43,10 @@ github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZX
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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/miekg/dns v1.1.58 h1:ca2Hdkz+cDg/7eNF6V56jjzuZ4aCAE+DbVkILdQWG/4=
github.com/miekg/dns v1.1.58/go.mod h1:Ypv+3b/KadlvW9vJfXOTf300O4UqaHFzFCuHz+rPkBY=
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=
@ -54,8 +65,9 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
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.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
@ -63,21 +75,26 @@ github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZ
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc=
golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
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.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

171
main.go
View File

@ -1,17 +1,182 @@
package main
import (
"embed"
"encoding/json"
"html/template"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
//go:embed pages
var embeddedFiles embed.FS
type transport struct {
apiKey string
underlyingTransport http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.apiKey != "" {
req.Header.Add("Authorization", "token "+t.apiKey)
}
return t.underlyingTransport.RoundTrip(req)
}
func main() {
godotenv.Load()
rootDomain, exists := os.LookupEnv("ROOT_DOMAIN")
if !exists {
rootDomain = "localhost"
}
giteaUrl, exists := os.LookupEnv("GITEA_URL")
if !exists {
giteaUrl = "https://codeberg.org"
}
defaultRef, exists := os.LookupEnv("DEFAULT_REF")
if !exists {
defaultRef = "pages"
}
indexFile, exists := os.LookupEnv("INDEX_FILE")
if !exists {
indexFile = "index.html"
}
directoryIndexStr := os.Getenv("DIRECTORY_INDEX")
directoryIndex := true
if directoryIndexStr == "false" {
directoryIndex = false
}
defaultUser := os.Getenv("DEFAULT_USER")
servePort, exists := os.LookupEnv("SERVE_PORT")
if !exists {
servePort = "8080"
}
giteaToken := os.Getenv("GITEA_TOKEN")
gitea := http.Client{Transport: &transport{underlyingTransport: http.DefaultTransport, apiKey: giteaToken}}
r := gin.Default()
templ := template.Must(template.New("").ParseFS(embeddedFiles, "pages/*"))
r.SetHTMLTemplate(templ)
r.GET("/*path", func(ctx *gin.Context) {
path := ctx.Params.ByName("path")
host := strings.Split(ctx.Request.Host, ".")
ctx.JSON(200, gin.H{"host": host, "path": path})
rawHost := ctx.Request.Host
if !strings.HasSuffix(rawHost, rootDomain) {
ctx.HTML(404, "error.html", gin.H{
"error_code": "400",
"error_message": "invalid root domain",
})
return
}
hostPrefix := strings.TrimSuffix(rawHost, rootDomain)
host := strings.Split(hostPrefix, ".")
var owner string
switch len(host) - 1 {
case 0:
ctx.HTML(200, "index.html", gin.H{
"root_domain": rootDomain,
})
return
case 2:
owner = host[1]
case 1:
if defaultUser == "" {
goto godefault
}
owner = defaultUser
break
godefault:
fallthrough
default:
ctx.HTML(400, "index.html", gin.H{
"root_domain": rootDomain,
})
return
}
repo := host[0]
contentPath := giteaUrl + "/api/v1/repos/" + owner + "/" + repo + "/contents/" + path + "?ref=" + defaultRef
apiPath := giteaUrl + "/api/v1/repos/" + owner + "/" + repo + "/raw" + path
resp, err := gitea.Get(apiPath + "?ref=" + defaultRef)
if err != nil {
ctx.AbortWithError(500, err)
}
body, _ := io.ReadAll(resp.Body)
var message struct {
Message string
}
if resp.StatusCode == 200 {
// if file found
ct := mime.TypeByExtension(filepath.Ext(path))
ctx.Data(200, ct, body)
} else {
// if file not found, and get err message
json.Unmarshal(body, &message)
if message.Message != "getBlobForEntry" && path != "/" {
ctx.HTML(404, "error.html", gin.H{
"error_code": "404",
"error_message": "file not found",
})
return
}
// check is index file (from env) exists
indexPath := apiPath + "/" + indexFile + "?ref=" + defaultRef
resp, _ := gitea.Get(indexPath)
if resp.StatusCode == 200 {
// index file exist
body, _ := io.ReadAll(resp.Body)
ctx.Data(200, "text/html", body)
return
} else {
// else this is directory
resp, _ := gitea.Get(contentPath)
body, _ := io.ReadAll(resp.Body)
var dir []struct {
Name string
Path string
}
json.Unmarshal(body, &dir)
if len(dir) == 0 {
// zero files, empty or non-existent repo
ctx.HTML(404, "error.html", gin.H{
"error_code": "404",
"error_message": "pages for repository not found",
})
return
}
if !directoryIndex {
// if directory index disabled
ctx.HTML(401, "error.html", gin.H{
"error_code": "401",
"error_message": "directory index disabled",
})
return
}
var html string
html += "<h1>Index of " + path + "</h1>"
html += "<a href=\"" + filepath.Dir(path) + "\">Parrent directory</a><br/>"
for _, file := range dir {
html += "<a href=\"/" + file.Path + "\">" + file.Name + "</a><br/>"
}
ctx.Data(200, "text/html", []byte(html))
return
}
}
//ctx.JSON(200, gin.H{"host": host, "path": path})
})
r.Run()
r.Run(":" + servePort)
}

47
nginx.conf Normal file
View File

@ -0,0 +1,47 @@
worker_processes 1;
events { worker_connections 1024; }
http {
sendfile on;
large_client_header_buffers 4 32k;
upstream web-api {
server localhost:8080;
}
server {
listen 80 default_server;
server_name _;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name _;
ssl_certificate /etc/ssl/cert.crt;
ssl_certificate_key /etc/ssl/priv.key;
location / {
proxy_pass http://web-api;
proxy_redirect off;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
}
}

42
pages/error.html Normal file
View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .error_code }}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+128+Text&family=Titillium+Web:ital,wght@0,200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700&display=swap" rel="stylesheet">
<style>
html, body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
margin: 0;
font-family: "Titillium Web", sans-serif;
font-weight: 400;
font-size: 24px;
color-scheme: light dark;
background-color: Canvas;
color: CanvasText;
}
h1 {
font-family: "Libre Barcode 128 Text", system-ui;
font-weight: 400;
font-style: normal;
font-size: 72px;
}
</style>
</head>
<body>
<div class="center">
<h1>{{ .error_code }}</h1>
<p>{{ .error_message }}</p>
</div>
</body>
</html>

46
pages/index.html Normal file
View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>gitea pages</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+128+Text&family=Titillium+Web:ital,wght@0,200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700&display=swap" rel="stylesheet">
<style>
html, body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
margin: 0;
font-family: "Titillium Web", sans-serif;
font-weight: 400;
font-size: 24px;
color-scheme: light dark;
background-color: Canvas;
color: CanvasText;
}
h1 {
font-family: "Libre Barcode 128 Text", system-ui;
font-weight: 400;
font-style: normal;
font-size: 72px;
}
a {
color: CanvasText;
}
</style>
</head>
<body>
<div class="center">
<h1>gitea pages</h1>
<p>usage: repo.user.{{ .root_domain }}</p>
<a href="https://git.mi6e4ka.dev/mi6e4ka/gitea-pages"><small>source</small></a>
</div>
</body>
</html>