diff --git a/.env.dist b/.env.dist index 78f32ff..948c4e1 100644 --- a/.env.dist +++ b/.env.dist @@ -1,11 +1,15 @@ SERVER_ADDR=:80 -APP_NAME=auth-svc -APP_DOMAIN=auth.egosport -APP_PATH_PREFIX= -APP_KV_NAMESPACE=egosport/auth-svc +APP_NAME=identity-svc +APP_DOMAIN=identity.service.ego.io +REGISTRY_USE_DOMAIN_OVER_IP=false +APP_PATH_PREFIX=/identity +APP_KV_NAMESPACE=dev.egommerce/service/identity-svc -LOGGER_ADDR=logger.egosport:24224 -DATABASE_URL=postgres://egosport:12345678@db.egosport:5432/egosport -CACHE_ADDR=cache.egosport:6379 +LOGGER_ADDR=api-logger:24224 +REGISTRY_ADDR=api-registry:8500 +DATABASE_URL=postgres://postgres:12345678@postgres-db:5432/egommerce +CACHE_ADDR=api-cache:6379 CACHE_PASSWORD=12345678 +MONGODB_URL=mongodb://mongodb:12345678@mongo-db:27017 +# EVENTBUS_URL=amqp://guest:guest@api-eventbus:5672 \ No newline at end of file diff --git a/.gitignore b/.gitignore index db2ba47..4c1faf5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,6 @@ -# ---> Go -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - .env +.env.* +!.env.dist -# Dependency directories (remove the comment below to include it) -vendor/ - +.vscode/ +__debug_bin \ No newline at end of file diff --git a/Dockerfile.target b/Dockerfile.target index 996b273..e550ff2 100644 --- a/Dockerfile.target +++ b/Dockerfile.target @@ -11,11 +11,11 @@ ARG SVC_VER ARG BIN_OUTPUT ARG BUILD_TIME -LABEL dev.egosport.image.author="Piotr Biernat" -LABEL dev.egosport.image.vendor="Egosport" -LABEL dev.egosport.image.service=${SVC_NAME} -LABEL dev.egosport.image.version=${SVC_VER} -LABEL dev.egosport.image.build_time=${BUILD_TIME} +LABEL dev.egommerce.image.author="Piotr Biernat" +LABEL dev.egommerce.image.vendor="Egommerce" +LABEL dev.egommerce.image.service=${SVC_NAME} +LABEL dev.egommerce.image.version=${SVC_VER} +LABEL dev.egommerce.image.build_time=${BUILD_TIME} WORKDIR / COPY --from=builder $BIN_OUTPUT /app diff --git a/bin/entrypoint.sh b/bin/entrypoint.sh index fc4264e..384ab50 100755 --- a/bin/entrypoint.sh +++ b/bin/entrypoint.sh @@ -14,8 +14,8 @@ waitForService() done } -waitForService "db:5432" -waitForService "logger:24224" +waitForService "postgres-db:5432" +waitForService "api-logger:24224" # run migrations migrate.sh diff --git a/deploy/image-build.sh b/deploy/image-build.sh index 2a8b7ab..5c021c8 100755 --- a/deploy/image-build.sh +++ b/deploy/image-build.sh @@ -1,8 +1,8 @@ #!/bin/sh # RUN IN REPO ROOT DIR !! -export IMAGE_PREFIX="git.pbiernat.dev/egosport/identity" -export BUILDER_IMAGE="egosport-builder:identity" +export IMAGE_PREFIX="git.pbiernat.io/egommerce/identity" +export BUILDER_IMAGE="egommerce-builder:identity" export BUILD_TIME=$(date +"%Y%m%d%H%M%S") export SERVER_IMAGE="$IMAGE_PREFIX-svc" export DOCKER_BUILDKIT=1 @@ -17,12 +17,12 @@ docker build --rm -t $BUILDER_IMAGE -f Dockerfile.builder . if [ $TARGET = "latest" ] then # SERVER - docker build --build-arg SVC_NAME=identity-svc --build-arg SVC_VER="1.0" --build-arg BIN_OUTPUT=/go/bin/server \ + docker build --build-arg SVC_NAME=identity-service --build-arg SVC_VER="1.0" --build-arg BIN_OUTPUT=/go/bin/server \ --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --cache-from $SERVER_IMAGE:$TARGET -t $SERVER_IMAGE:$TARGET \ -f Dockerfile.target . >/dev/null 2>&1 && echo "Successfully tagged $SERVER_IMAGE:$TARGET" else # SERVER - docker build --build-arg SVC_NAME=identity-svc --build-arg SVC_VER="dev" --build-arg BIN_OUTPUT=/go/bin/server \ + docker build --build-arg SVC_NAME=identity-service --build-arg SVC_VER="dev" --build-arg BIN_OUTPUT=/go/bin/server \ --build-arg BUILDER_IMAGE=$BUILDER_IMAGE --build-arg BUILD_TIME --rm --no-cache -t $SERVER_IMAGE:$TARGET \ -f Dockerfile.target . >/dev/null 2>&1 && echo "Successfully tagged $SERVER_IMAGE:$TARGET" fi diff --git a/deploy/image-push.sh b/deploy/image-push.sh index d91aec1..6543fb4 100755 --- a/deploy/image-push.sh +++ b/deploy/image-push.sh @@ -1,13 +1,16 @@ #!/bin/sh # RUN IN REPO ROOT DIR !! -export IMAGE_BASE="git.pbiernat.dev/egosport/identity" -export SERVER_IMAGE="$IMAGE_BASE-svc" -# export WORKER_IMAGE="$IMAGE_BASE-worker" +export IMAGE_PREFIX="git.pbiernat.io/egommerce/identity" +export SERVER_IMAGE="$IMAGE_PREFIX-svc" +# export WORKER_IMAGE="$IMAGE_PREFIX-worker" TARGET=${1:-latest} -echo $DOCKER_PASSWORD | docker login git.pbiernat.dev -u $DOCKER_USERNAME --password-stdin +echo $DOCKER_PASSWORD | docker login git.pbiernat.io -u $DOCKER_USERNAME --password-stdin docker push "$SERVER_IMAGE:$TARGET" # docker push "$WORKER_IMAGE:$TARGET" + +# Restart container +curl -X POST http://127.0.0.1:9001/api/webhooks/64ea5d78-ae21-474c-ad4d-1d98f6b83acb diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..94e30ce --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,18 @@ +# ---> Go +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +.env + +# Dependency directories (remove the comment below to include it) +vendor/ diff --git a/src/cmd/migrate/main.go b/src/cmd/migrate/main.go index 0e66d82..5664ea3 100644 --- a/src/cmd/migrate/main.go +++ b/src/cmd/migrate/main.go @@ -9,16 +9,17 @@ import ( "github.com/go-pg/migrations/v8" "github.com/go-pg/pg/v10" - "git.pbiernat.dev/egommerce/go-api-pkg/fluentd" + "git.pbiernat.io/egommerce/go-api-pkg/fluentd" - baseCnf "git.pbiernat.dev/egommerce/go-api-pkg/config" - cnf "git.pbiernat.dev/egosport/identity-svc/internal/config" + baseCnf "git.pbiernat.io/egommerce/go-api-pkg/config" + cnf "git.pbiernat.io/egommerce/identity-service/internal/server" ) const ( - defAppName = "identity-svc-migrations" + defAppName = "identity-service-migrations" defMigrationsTableName = "identity.migrations" defLoggerAddr = "api-logger:24224" + // defKVNmspc = "dev.egommerce/service/identity-migration" ) const usageText = `This program runs command on the db. Supported commands are: @@ -34,7 +35,11 @@ Usage: ` func main() { - flag.Usage = usage + flag.Usage = func() { + fmt.Print(usageText) + flag.PrintDefaults() + os.Exit(2) + } flag.Parse() if baseCnf.ErrLoadingEnvs != nil { @@ -43,6 +48,8 @@ func main() { c := cnf.NewConfig("migrator") + // dbURL := baseCnf.GetEnv("DATABASE_URL", defDbURL) + logHost, logPort, err := fluentd.ParseAddr(c.LoggerAddr) if err != nil { log.Fatalf("Error parsing logger addr: %s. Err: %v", c.LoggerAddr, err) @@ -56,9 +63,9 @@ func main() { db := pg.Connect(&pg.Options{ // FIXME Addr: "db:5432", - User: "egosport", + User: "egommerce", Password: "12345678", - Database: "egosport", + Database: "egommerce", }) defer db.Close() @@ -79,12 +86,5 @@ func main() { } else { logger.Log("version is %d\n", oldVersion) } - - os.Exit(0) -} - -func usage() { - fmt.Print(usageText) - flag.PrintDefaults() - os.Exit(2) + // os.Exit(0) } diff --git a/src/cmd/server/main.go b/src/cmd/server/main.go index ec9ae9d..0eca564 100644 --- a/src/cmd/server/main.go +++ b/src/cmd/server/main.go @@ -1,31 +1,34 @@ package main import ( + "fmt" "log" "os" - baseCnf "git.pbiernat.dev/egosport/identity-svc/pkg/config" + cnf "git.pbiernat.io/egommerce/go-api-pkg/config" - cnf "git.pbiernat.dev/egosport/identity-svc/internal/config" - svr "git.pbiernat.dev/egosport/identity-svc/internal/server" + "git.pbiernat.io/egommerce/identity-service/internal/app" + "git.pbiernat.io/egommerce/identity-service/internal/server" ) func main() { - if baseCnf.ErrLoadingEnvs != nil { - log.Panicln("Error loading .env file", baseCnf.ErrLoadingEnvs) + if cnf.ErrLoadingEnvs != nil { + log.Panicln("Error loading .env file", cnf.ErrLoadingEnvs) } - c := cnf.NewConfig("svc") - srv := svr.New( - c, - svr.WithCache(c), - svr.WithDatabase(c), - svr.WithLogger(c), - // svr.WithRegistry(c), - ) + c := server.NewConfig("identity") + cArr := c.GetArray() + + doer := server.New(c) + a := app.NewApp(doer) + a.RegisterPlugin(app.LoggerPlugin(cArr)) + a.RegisterPlugin(app.CachePlugin(cArr)) + a.RegisterPlugin(app.DatabasePlugin(cArr)) + // a.RegisterPlugin(app.EventbusPlugin(cArr)) + a.RegisterPlugin(app.RegistryPlugin(cArr)) while := make(chan struct{}) - err := srv.Base.Start(while /*, srv.Shutdown()*/) + err := a.Start(while) <-while if err != nil { @@ -33,5 +36,6 @@ func main() { os.Exit(1) } + fmt.Println("Gone") os.Exit(0) } diff --git a/src/go.mod b/src/go.mod index 5fa45de..cd22d97 100644 --- a/src/go.mod +++ b/src/go.mod @@ -1,17 +1,18 @@ -module git.pbiernat.dev/egosport/identity-svc +module git.pbiernat.io/egommerce/identity-service go 1.18 require ( - git.pbiernat.dev/egommerce/api-entities v0.0.26 - git.pbiernat.dev/egommerce/go-api-pkg v0.1.66 + git.pbiernat.io/egommerce/api-entities v0.2.3 + git.pbiernat.io/egommerce/go-api-pkg v0.2.88 github.com/go-pg/migrations/v8 v8.1.0 github.com/go-pg/pg/v10 v10.11.1 github.com/go-redis/redis/v8 v8.11.5 - github.com/gofiber/fiber/v2 v2.49.2 + github.com/gofiber/fiber/v2 v2.52.4 + github.com/gofiber/jwt/v2 v2.2.7 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/jackc/pgx/v5 v5.4.3 - github.com/joho/godotenv v1.5.1 + github.com/rabbitmq/amqp091-go v1.10.0 ) require ( @@ -39,7 +40,7 @@ require ( github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/btree v1.1.2 // indirect - github.com/google/uuid v1.3.1 // indirect + github.com/google/uuid v1.5.0 // indirect github.com/hashicorp/consul v1.16.2 // indirect github.com/hashicorp/consul-net-rpc v0.0.0-20230315140415-c045f395701f // indirect github.com/hashicorp/consul/api v1.25.1 // indirect @@ -69,9 +70,10 @@ require ( github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect + github.com/joho/godotenv v1.5.1 // indirect github.com/klauspost/compress v1.17.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/miekg/dns v1.1.56 // indirect @@ -98,18 +100,18 @@ require ( github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasthttp v1.50.0 // indirect + github.com/valyala/fasthttp v1.51.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect github.com/vmihailenco/bufpool v0.1.11 // indirect github.com/vmihailenco/msgpack/v5 v5.4.0 // indirect github.com/vmihailenco/tagparser v0.1.2 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect - golang.org/x/crypto v0.13.0 // indirect + golang.org/x/crypto v0.14.0 // indirect golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect golang.org/x/mod v0.12.0 // indirect - golang.org/x/net v0.15.0 // indirect + golang.org/x/net v0.17.0 // indirect golang.org/x/sync v0.3.0 // indirect - golang.org/x/sys v0.12.0 // indirect + golang.org/x/sys v0.15.0 // indirect golang.org/x/text v0.13.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.13.0 // indirect diff --git a/src/go.sum b/src/go.sum index abcb43e..316e10e 100644 --- a/src/go.sum +++ b/src/go.sum @@ -5,10 +5,10 @@ cloud.google.com/go/compute v1.23.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdi cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/iam v1.1.1 h1:lW7fzj15aVIXYHREOqjRBV9PsH0Z6u8Y46a1YGvQP4Y= cloud.google.com/go/iam v1.1.1/go.mod h1:A5avdyVL2tCppe4unb0951eI9jreack+RJ0/d+KUZOU= -git.pbiernat.dev/egommerce/api-entities v0.0.26 h1:Avz02GINwuYWOjw1fmZIJ3QgGEIz3a5vRQZNaxxUQIk= -git.pbiernat.dev/egommerce/api-entities v0.0.26/go.mod h1:+BXvUcr6Cr6QNpJsW8BUfe1vVILdWDADNE0e3u0lNvU= -git.pbiernat.dev/egommerce/go-api-pkg v0.1.66 h1:CRJYVSIZ8iolu3LQM9hAcImniM5u9+EYFRUR2bY0Emk= -git.pbiernat.dev/egommerce/go-api-pkg v0.1.66/go.mod h1:nzsa99OyjTHGT5KK294iPzDEjtDFdkcHYejcpDDTL6M= +git.pbiernat.io/egommerce/api-entities v0.2.3 h1:mR6EYfZkAzh4teydb7KXDBWoxwVW3qasnmmH5J3mnas= +git.pbiernat.io/egommerce/api-entities v0.2.3/go.mod h1:INXAG5x4+i+vNwg1NpfPHiDW8nY1kn1K7pgLOtX+/I0= +git.pbiernat.io/egommerce/go-api-pkg v0.2.88 h1:xya/39BnFeha3Oc76ad/ppoQd6AstTGQd87Qszamr1A= +git.pbiernat.io/egommerce/go-api-pkg v0.2.88/go.mod h1:XIy2mmvRNIzQmYIUAcDZafhRPxTQFS2HDmsK7ZQ6980= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest/autorest v0.11.28 h1:ndAExarwr5Y+GaHE6VCaY1kyS/HwwGGyuimVhWsHOEM= @@ -33,6 +33,7 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/aliyun/alibaba-cloud-sdk-go v1.62.156 h1:K4N91T1+RlSlx+t2dujeDviy4ehSGVjEltluDgmeHS4= +github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e h1:QEF07wC0T1rKkctt1RINW/+RMTVmiwxETico2l3gxJA= @@ -133,12 +134,16 @@ github.com/go-pg/zerochecker v0.2.0/go.mod h1:NJZ4wKL0NmTtz0GKCoJ8kym6Xn/EQzXRl2 github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gofiber/fiber/v2 v2.49.2 h1:ONEN3/Vc+dUCxxDgZZwpqvhISgHqb+bu+isBiEyKEQs= -github.com/gofiber/fiber/v2 v2.49.2/go.mod h1:gNsKnyrmfEWFpJxQAV0qvW6l70K1dZGno12oLtukcts= +github.com/gofiber/fiber/v2 v2.17.0/go.mod h1:iftruuHGkRYGEXVISmdD7HTYWyfS2Bh+Dkfq4n/1Owg= +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/jwt/v2 v2.2.7 h1:MgXZV+ak+FiRVepD3btHBxWcyxlFzTDGXJv78dU1sIE= +github.com/gofiber/jwt/v2 v2.2.7/go.mod h1:yaOHLccYXJidk1HX/EiIdIL+Z1xmY2wnIv6hgViw384= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -159,6 +164,7 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= @@ -176,8 +182,8 @@ github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASu github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= +github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= github.com/googleapis/gax-go/v2 v2.11.0 h1:9V9PWXEsWnPpQhu/PeQIkS4eGzMlTLGgt80cUUI8Ki4= github.com/gophercloud/gophercloud v0.3.0 h1:6sjpKIpVwRIIwmcEGp+WwNovNsem+c+2vm6oxshRpL8= @@ -299,6 +305,7 @@ github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCV github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/klauspost/compress v1.12.2/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -325,8 +332,8 @@ github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOA github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -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/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -421,6 +428,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= +github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= +github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/renier/xmlrpc v0.0.0-20170708154548-ce4a1a486c03 h1:Wdi9nwnhFNAlseAOekn6B5G/+GMtks9UKbvRU/CMM/o= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= @@ -469,8 +478,9 @@ github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c h1:u6SKchux2yDvFQnDH github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c/go.mod h1:hzIxponao9Kjc7aWznkXaL4U4TWaDSs8zcsY4Ka08nM= 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.50.0 h1:H7fweIlBm0rXLs2q0XbalvJ6r0CUPFWK3/bB4N13e9M= -github.com/valyala/fasthttp v1.50.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA= +github.com/valyala/fasthttp v1.26.0/go.mod h1:cmWIqlu99AO/RKcp1HWaViTqc57FswJOfYYdPJBl8BA= +github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= +github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= @@ -499,8 +509,8 @@ go.opentelemetry.io/otel/sdk/metric v0.39.0 h1:Kun8i1eYf48kHH83RucG93ffz0zGV1sh4 go.opentelemetry.io/otel/trace v1.16.0 h1:8JRpaObFoW0pxuVPapkgH8UhHQj+bJW8jJsCZEu5MQs= go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -509,10 +519,11 @@ golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= -golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= @@ -520,7 +531,6 @@ golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= @@ -544,11 +554,12 @@ golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201016165138-7b1cca2348c0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= +golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= -golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -589,6 +600,8 @@ golang.org/x/sys v0.0.0-20201017003518-b09fb700fbb7/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -600,13 +613,13 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.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/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.12.0 h1:/ZfYdc3zq+q02Rv9vGqTeSItdzZTSNDmfTi0mBAuidU= +golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= diff --git a/src/internal/app/app.go b/src/internal/app/app.go new file mode 100644 index 0000000..26225c9 --- /dev/null +++ b/src/internal/app/app.go @@ -0,0 +1,81 @@ +package app + +import ( + "log" + "os" + "os/signal" + "strconv" + "syscall" +) + +type ( + Doer interface { + Start() error + RegisterHandler(string, func() any) + OnShutdown() + } + Application interface { + Start(while chan struct{}) + RegisterPlugin(PluginFn) error + Shutdown() + } + + App struct { + doer Doer + } +) + +func NewApp(d Doer) *App { + return &App{ + doer: d, + } +} + +func (a *App) Start(while chan struct{}) error { + go func() { + sigint := make(chan os.Signal, 1) + signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + <-sigint + + a.Shutdown() + + close(while) + }() + + run := a.createRunFile("./app.run") // FIXME path... + defer a.removeRunFile(run) + + err := a.doer.Start() + if err != nil { + log.Fatalf("Failed to start app. Reason: %v\n", err) + close(while) + } + <-while + + return err +} + +func (a *App) RegisterPlugin(p Plugin) error { + a.doer.RegisterHandler(p.name, p.fn) + + return nil +} + +func (a *App) Shutdown() { + a.doer.OnShutdown() +} + +func (a *App) createRunFile(path string) *os.File { + run, err := os.Create(path) + if err != nil { + log.Fatalf("Failed to create run file. Reason: %v\n", err) + os.Exit(1) + } + run.WriteString(strconv.Itoa(os.Getpid())) + + return run +} + +func (a *App) removeRunFile(f *os.File) error { + return f.Close() +} diff --git a/src/internal/app/plugins.go b/src/internal/app/plugins.go new file mode 100644 index 0000000..1a66260 --- /dev/null +++ b/src/internal/app/plugins.go @@ -0,0 +1,138 @@ +package app + +import ( + "log" + "os" + "strconv" + + redis "github.com/go-redis/redis/v8" + + "git.pbiernat.io/egommerce/go-api-pkg/consul" + "git.pbiernat.io/egommerce/go-api-pkg/fluentd" + + db "git.pbiernat.io/egommerce/identity-service/pkg/database" +) + +type ( + Plugin struct { + name string + fn PluginFn + } + PluginFn func() any +) + +func CachePlugin(cArr map[string]string) Plugin { + return Plugin{ + name: "cache", + fn: func() any { + return redis.NewClient(&redis.Options{ + Addr: cArr["cacheAddr"], + Password: cArr["cachePassword"], + DB: 0, + }) + }, + } +} + +func DatabasePlugin(cArr map[string]string) Plugin { + return Plugin{ + name: "database", + fn: func() any { + dbConn, err := db.Connect(cArr["dbURL"]) + if err != nil { + log.Fatalf("Failed to connect to the Database: %s. Err: %v\n", cArr["dbURL"], err) + os.Exit(1) // TODO: retry in background... + } + + return dbConn + }, + } +} + +// func EventbusPlugin(cArr map[string]string) Plugin { +// return Plugin{ +// name: "eventbus", +// fn: func() any { +// conn, err := amqp.Dial(cArr["eventBusURL"]) +// if err != nil { +// log.Fatalf("Failed to connect to the EventBus: %s. Err: %v\n", cArr["eventBusURL"], err) +// os.Exit(1) // TODO: retry in background... +// } + +// chn, err := conn.Channel() +// if err != nil { +// log.Fatalf("Failed to open new EventBus channel. Err: %v\n", err) +// os.Exit(1) // TODO: retry in background... +// } + +// return chn +// }, +// } +// } + +func LoggerPlugin(cArr map[string]string) Plugin { + return Plugin{ + name: "logger", + fn: func() any { + logHost, logPort, err := fluentd.ParseAddr(cArr["loggerAddr"]) + if err != nil { + log.Fatalf("Failed to parse FluentD address: %s. Err: %v", cArr["loggerAddr"], err) + os.Exit(1) // TODO: retry in background... + } + + logger, err := fluentd.NewLogger(cArr["appFullname"], logHost, logPort) + if err != nil { + log.Fatalf("Failed to connect to the FluentD on %s:%d. Err: %v", logHost, logPort, err) + os.Exit(1) // TODO: retry in background... + } + + return logger + }, + } +} + +func RegistryPlugin(cArr map[string]string) Plugin { + return Plugin{ + name: "registry", + fn: func() any { + port, _ := strconv.Atoi(cArr["netAddr"][1:]) // FIXME: can be IP:PORT or :PORT + // log.Printf("Consul retrieved port: %v", port) + registry, err := consul.NewService(cArr["registryAddr"], cArr["id"], cArr["name"], cArr["registryDomainOverIP"], cArr["ip"], cArr["domain"], cArr["pathPrefix"], port) + if err != nil { + log.Fatalf("Failed to connect to the Consul on: %s. Err: %v", cArr["registryAddr"], err) + os.Exit(1) // TODO: retry in background... + } + + err = registry.Register() + if err != nil { + log.Fatalf("Failed to register in the Consul service. Err: %v", err) + os.Exit(1) // TODO: retry in background... + } + + registry.RegisterHealthChecks() + // a.registerKVUpdater() // FIXME run as goroutine + + return registry + + // svc, _ := registry.Connect() + // tlsCnf := svc.ServerTLSConfig() + // s.Base.App.Server().TLSConfig = tlsCnf + // fmt.Println("Podmiana configa TLS") + // defer svc.Close() + + // go func() { // Consul KV updater + // ticker := time.NewTicker(time.Second * 15) + // for range ticker.C { + // fetchKVConfig(s) // FIXME: duplicated in worker + // } + // }() + + // go func() { // Server metadata cache updater + // ticker := time.NewTicker(time.Second * 5) + // for range ticker.C { + // s.cacheMetadata() + // } + // }() + }, + } +} diff --git a/src/internal/config/config.go b/src/internal/config/config.go deleted file mode 100644 index 87d99b4..0000000 --- a/src/internal/config/config.go +++ /dev/null @@ -1,55 +0,0 @@ -package common - -import ( - "os" - - cnf "git.pbiernat.dev/egosport/identity-svc/pkg/config" - srv "git.pbiernat.dev/egosport/identity-svc/pkg/server" -) - -const ( - defAppName = "api-svc" - defAppDomain = "api-svc" - defCacheAddr = "cache:6379" - defCachePassword = "12345678" - defDbURL = "postgres://egosport:12345678@db.egosport:5432/egosport" - defKVNmspc = "egosport/api" - defLoggerAddr = "logger.egosport:24224" - defNetAddr = ":80" - defPathPrefix = "/api" -) - -type Config struct { - Base *srv.Config - - DbURL string `json:"db_url"` - CacheAddr string `json:"cache_addr"` - CachePassword string `json:"cache_password"` - EventBusExchange string `json:"eventbus_exchange"` - EventBusQueue string `json:"eventbus_queue"` - EventBusURL string `json:"eventbus_url"` - LoggerAddr string `json:"logger_addr"` - KVNamespace string - RegistryAddr string - - // Fields with JSON mappings are available through Consul KV storage -} - -func NewConfig(name string) *Config { - c := new(Config) - c.Base = new(srv.Config) - - c.Base.AppID, _ = os.Hostname() - c.Base.AppName = name - c.Base.NetAddr = cnf.GetEnv("SERVER_ADDR", defNetAddr) - c.Base.PathPrefix = cnf.GetEnv("APP_PATH_PREFIX", defPathPrefix) - - c.CacheAddr = cnf.GetEnv("CACHE_ADDR", defCacheAddr) - c.CachePassword = cnf.GetEnv("CACHE_PASSWORD", defCachePassword) - c.DbURL = cnf.GetEnv("DATABASE_URL", defDbURL) - c.KVNamespace = cnf.GetEnv("APP_KV_NAMESPACE", defKVNmspc) - c.LoggerAddr = cnf.GetEnv("LOGGER_ADDR", defLoggerAddr) - // c.RegistryAddr = cnf.GetEnv("REGISTRY_ADDR", defRegistryAddr) - - return c -} diff --git a/src/internal/app/definition/error.go b/src/internal/domain/definition/error.go similarity index 100% rename from src/internal/app/definition/error.go rename to src/internal/domain/definition/error.go diff --git a/src/internal/app/entity/user.go b/src/internal/domain/entity/user.go similarity index 100% rename from src/internal/app/entity/user.go rename to src/internal/domain/entity/user.go diff --git a/src/internal/app/handler/error.go b/src/internal/domain/handler/error.go similarity index 100% rename from src/internal/app/handler/error.go rename to src/internal/domain/handler/error.go diff --git a/src/internal/app/handler/secret.go b/src/internal/domain/handler/secret.go similarity index 100% rename from src/internal/app/handler/secret.go rename to src/internal/domain/handler/secret.go diff --git a/src/internal/app/log.go b/src/internal/domain/log.go similarity index 87% rename from src/internal/app/log.go rename to src/internal/domain/log.go index fa33d99..8ce89e4 100644 --- a/src/internal/app/log.go +++ b/src/internal/domain/log.go @@ -4,7 +4,7 @@ import ( "log" ) -const AppName = "identity-svc" +const AppName = "identity-service" func Panic(v ...any) { log.Panicln(AppName+":", v) diff --git a/src/internal/app/middleware/jwt.go b/src/internal/domain/middleware/jwt.go similarity index 100% rename from src/internal/app/middleware/jwt.go rename to src/internal/domain/middleware/jwt.go diff --git a/src/internal/server/config.go b/src/internal/server/config.go index 5213283..cc41c5a 100644 --- a/src/internal/server/config.go +++ b/src/internal/server/config.go @@ -1,16 +1,42 @@ package server -import "fmt" +import ( + "fmt" + "net" + "os" + "time" + + cnf "git.pbiernat.io/egommerce/go-api-pkg/config" +) + +const ( + defName = "identity-svc" + defDomain = "identity-svc" + defCacheAddr = "egommerce.local:6379" + defCachePassword = "12345678" + defDbURL = "postgres://postgres:12345678@db-postgres:5432/egommerce" + defEventBusURL = "amqp://guest:guest@api-eventbus:5672" + defKVNmspc = "dev.egommerce/service/identity" + defLoggerAddr = "api-logger:24224" + defNetAddr = ":80" + defMongoDbURL = "mongodb://mongodb:12345678@mongo-db:27017" + defPathPrefix = "/identity" + defRegistryAddr = "api-registry:8500" + defEbEventsExchange = "api-events" + defEbEventsQueue = "identity-svc" +) type Config struct { - AppID string - AppName string - AppDomain string - PathPrefix string - NetAddr string - Port int - RegistryAddr string - KVNamespace string + ID string + Name string + Domain string + NetAddr string + RegistryDomainOverIP string + PathPrefix string + + IdleTimeout time.Duration // miliseconds + ReadTimeout time.Duration // miliseconds + WriteTimeout time.Duration // miliseconds LoggerAddr string `json:"logger_addr"` DbURL string `json:"db_url"` @@ -20,12 +46,66 @@ type Config struct { EventBusURL string `json:"eventbus_url"` EventBusExchange string `json:"eventbus_exchange"` EventBusQueue string `json:"eventbus_queue"` - HttpReadTimeout int `json:"http_read_timeout"` - HttpWriteTimeout int `json:"http_write_timeout"` - HttpIdleTimeout int `json:"http_idle_timeout"` - // Fields with json mapping are available trough ConsulKV + KVNamespace string + RegistryAddr string + + // Fields with JSON mappings are available through Consul KV storage +} + +func NewConfig(name string) *Config { + c := new(Config) + + c.ID, _ = os.Hostname() + c.Name = name + c.Domain = cnf.GetEnv("APP_DOMAIN", defDomain) + c.NetAddr = cnf.GetEnv("SERVER_ADDR", defNetAddr) + c.RegistryDomainOverIP = cnf.GetEnv("REGISTRY_USE_DOMAIN_OVER_IP", "false") + c.PathPrefix = cnf.GetEnv("APP_PATH_PREFIX", defPathPrefix) + + c.CacheAddr = cnf.GetEnv("CACHE_ADDR", defCacheAddr) + c.CachePassword = cnf.GetEnv("CACHE_PASSWORD", defCachePassword) + c.DbURL = cnf.GetEnv("DATABASE_URL", defDbURL) + c.EventBusExchange = defEbEventsExchange + c.EventBusURL = cnf.GetEnv("EVENTBUS_URL", defEventBusURL) + c.KVNamespace = cnf.GetEnv("APP_KV_NAMESPACE", defKVNmspc) + c.LoggerAddr = cnf.GetEnv("LOGGER_ADDR", defLoggerAddr) + c.RegistryAddr = cnf.GetEnv("REGISTRY_ADDR", defRegistryAddr) + + return c } func (c *Config) GetAppFullName() string { - return fmt.Sprintf("%s_%s", c.AppName, c.AppID) + return fmt.Sprintf("%s_%s", c.Name, c.ID) +} + +func (c *Config) GetIP() string { + host, _ := os.Hostname() + ips, _ := net.LookupIP(host) + // for _, ip := range ips { + // return ip.String() + // } + + return ips[0].String() +} + +func (c *Config) GetArray() map[string]string { // FIXME fix types etc + arr := make(map[string]string) + arr["id"] = c.ID + arr["name"] = c.Name + arr["appFullname"] = c.GetAppFullName() + arr["domain"] = c.Domain + arr["ip"] = c.GetIP() + arr["netAddr"] = c.NetAddr + arr["registryDomainOverIP"] = c.RegistryDomainOverIP + arr["pathPrefix"] = c.PathPrefix + arr["cacheAddr"] = c.CacheAddr + arr["cachePassword"] = c.CachePassword + arr["dbURL"] = c.DbURL + arr["eventBusExchange"] = c.EventBusExchange + arr["eventBusURL"] = c.EventBusURL + arr["kvNamespace"] = c.KVNamespace + arr["loggerAddr"] = c.LoggerAddr + arr["registryAddr"] = c.RegistryAddr + + return arr } diff --git a/src/internal/server/login_handler.go b/src/internal/server/login_handler.go index 5433b75..b1be135 100644 --- a/src/internal/server/login_handler.go +++ b/src/internal/server/login_handler.go @@ -1,7 +1,7 @@ package server import ( - "git.pbiernat.dev/egosport/identity-svc/internal/service" + "git.pbiernat.io/egommerce/identity-service/internal/service" "github.com/gofiber/fiber/v2" ) @@ -26,6 +26,7 @@ func (s *Server) LoginHandler(c *fiber.Ctx) error { } cookie := service.AuthService.Cookie("auth_token", token) + // ^^ FIXME move cookkie creation to separate service c.Cookie(cookie) return c.JSON(&AuthLoginResponse{JWTToken: token}) diff --git a/src/internal/server/middleware.go b/src/internal/server/middleware.go index 74e2cda..61ad4d7 100644 --- a/src/internal/server/middleware.go +++ b/src/internal/server/middleware.go @@ -5,15 +5,15 @@ import ( "github.com/gofiber/fiber/v2" - "git.pbiernat.dev/egommerce/go-api-pkg/fluentd" + "git.pbiernat.io/egommerce/go-api-pkg/fluentd" ) // "github.com/gofiber/fiber/v2" // "github.com/gofiber/fiber/v2/middleware/cors" func SetupMiddleware(s *Server) { - s.Base.Use(defaultCORS) - s.Base.Use(LoggingMiddleware(s.Logger)) + s.Use(defaultCORS) + s.Use(LoggingMiddleware(s.GetLogger())) } func LoggingMiddleware(log *fluentd.Logger) func(c *fiber.Ctx) error { diff --git a/src/internal/server/router.go b/src/internal/server/router.go index 278dce9..43ed137 100644 --- a/src/internal/server/router.go +++ b/src/internal/server/router.go @@ -6,21 +6,21 @@ import ( var ( defaultCORS = cors.New(cors.Config{ - AllowOrigins: "*", - AllowCredentials: true, - AllowMethods: "GET, POST, PATCH, PUT, DELETE, OPTIONS", - AllowHeaders: "Accept, Authorization, Content-Type, Vary, X-Request-Id", + AllowOrigins: "*", + // AllowCredentials: true, + AllowMethods: "GET, POST, PATCH, PUT, DELETE, OPTIONS", + AllowHeaders: "Accept, Authorization, Content-Type, Vary, X-Request-Id", }) ) func SetupRouter(s *Server) { - s.Base.Options("*", defaultCORS) - s.Base.Use(defaultCORS) + s.Options("*", defaultCORS) + s.Use(defaultCORS) - s.Base.Get("/health", s.HealthHandler) - s.Base.Get("/config", s.ConfigHandler) + s.Get("/health", s.HealthHandler) + s.Get("/config", s.ConfigHandler) - api := s.Base.Group("/api") + api := s.Group("/api") v1 := api.Group("/v1") v1.Post("/login", s.LoginHandler) v1.All("/traefik", s.TraefikHandler) diff --git a/src/internal/server/server.go b/src/internal/server/server.go index 5fd406f..0b5d570 100644 --- a/src/internal/server/server.go +++ b/src/internal/server/server.go @@ -1,181 +1,135 @@ package server import ( - "log" - "os" + "net" + "time" "github.com/go-redis/redis/v8" + "github.com/gofiber/fiber/v2" "github.com/jackc/pgx/v5/pgxpool" - "git.pbiernat.dev/egommerce/go-api-pkg/consul" - "git.pbiernat.dev/egommerce/go-api-pkg/fluentd" - - db "git.pbiernat.dev/egosport/identity-svc/pkg/database" - p "git.pbiernat.dev/egosport/identity-svc/pkg/server" - - cnf "git.pbiernat.dev/egosport/identity-svc/internal/config" + "git.pbiernat.io/egommerce/api-entities/http" + "git.pbiernat.io/egommerce/go-api-pkg/consul" + "git.pbiernat.io/egommerce/go-api-pkg/fluentd" ) type ( Server struct { - Base *p.Server - Config *cnf.Config + *fiber.App - Cache *redis.Client - Database *pgxpool.Pool - Logger *fluentd.Logger - Registry *consul.Service + ID string + addr string // e.g. "127.0.0.1:80" + handlers map[string]any + } + HeaderRequestID struct { + RequestID string `reqHeader:"x-request-id"` } - - OptionFn func(*Server) error // FIXME: similar in worker ) -func New(c *cnf.Config, opts ...OptionFn) *Server { - svr := &Server{ - Base: p.New(c.Base), - Config: c, - } - - svr.Base.PurgeFn = svr.Shutdown() - - for _, opt := range opts { - if err := opt(svr); err != nil { - log.Fatalf("Failed to attach extension to the server. Err: %v\n", err) - } - } - - SetupMiddleware(svr) - SetupRouter(svr) - - return svr -} - -func WithCache(c *cnf.Config) OptionFn { - redis := redis.NewClient(&redis.Options{ - Addr: c.CacheAddr, - Password: c.CachePassword, - DB: 0, - }) - - return func(s *Server) error { - s.Cache = redis - - return nil +func New(c *Config) *Server { + return &Server{ + ID: c.ID, + App: fiber.New(fiber.Config{ + AppName: c.ID, + ServerHeader: c.Name + ":" + c.ID, + ReadTimeout: c.ReadTimeout * time.Millisecond, + WriteTimeout: c.WriteTimeout * time.Millisecond, + IdleTimeout: c.IdleTimeout * time.Millisecond, + }), + addr: c.NetAddr, + handlers: make(map[string]any), } } -func WithDatabase(c *cnf.Config) OptionFn { - dbConn, err := db.Connect(c.DbURL) - if err != nil { - log.Fatalf("Failed to connect to the Database: %s. Err: %v\n", c.DbURL, err) - os.Exit(1) - } +func (s *Server) Start() error { + SetupMiddleware(s) + SetupRouter(s) - return func(s *Server) error { - s.Database = dbConn + // fmt.Printf("Starting server at: %s...\n", s.addr) + ln, _ := net.Listen("tcp", s.addr) + // ln = tls.NewListener(ln, s.App.Server().TLSConfig) - return nil - } + return s.Listener(ln) } -func WithLogger(c *cnf.Config) OptionFn { - return func(s *Server) error { - logHost, logPort, err := fluentd.ParseAddr(c.LoggerAddr) - if err != nil { - log.Fatalf("Failed to parse Fluentd address: %s. Err: %v", c.LoggerAddr, err) - } - - logger, err := fluentd.NewLogger(c.Base.GetAppFullName(), logHost, logPort) - if err != nil { - log.Fatalf("Failed to connect to the Fluentd on %s:%d. Err: %v", logHost, logPort, err) - } - - s.Logger = logger - - return nil - } +func (s *Server) RegisterHandler(name string, fn func() any) { + // fmt.Printf("Registering plugin( with handler): %s... OK\n", name) + s.handlers[name] = fn() } -// func WithRegistry(c *cnf.Config) OptionFn { -// return func(s *Server) error { -// port, _ := strconv.Atoi(c.Base.NetAddr[1:]) // FIXME: can be IP:PORT which will cause error -// registry, err := consul.NewService(c.RegistryAddr, c.Base.AppID, c.Base.AppName, c.Base.AppID, c.Base.AppName, c.Base.PathPrefix, port) -// if err != nil { -// log.Fatalf("Failed to connect to the Consul on: %s. Err: %v", c.RegistryAddr, err) -// } +func (s *Server) OnShutdown() { + // s.GetLogger().Log("Server %s is going down...", s.ID) -// err = registry.Register() -// if err != nil { -// log.Fatalf("Failed to register in the Consul service. Err: %v", err) -// } + s.GetRegistry().Unregister() + // a.clearMetadataCache() + // s.GetEventBus().Close() + s.GetDatabase().Close() + s.GetLogger().Log("Gone.") + s.GetLogger().Close() -// s.Registry = registry + s.Shutdown() +} -// go func() { // Consul KV updater -// ticker := time.NewTicker(time.Second * 15) -// for range ticker.C { -// fetchKVConfig(s) // FIXME: duplicated in worker -// } -// }() +func (s *Server) GetRequestID(c *fiber.Ctx) (string, error) { + var hdr = new(HeaderRequestID) + if err := c.ReqHeaderParser(hdr); err != nil { + return "", err + } -// go func() { // Server metadata cache updater -// ticker := time.NewTicker(time.Second * 5) -// for range ticker.C { -// s.cacheMetadata() -// } -// }() + return hdr.RequestID, nil +} -// return nil -// } +func (s *Server) Error(c *fiber.Ctx, code int, msg string) error { + return c.Status(code).JSON(http.ErrorResponse{Error: msg}) +} + +// Plugin helper funcitons +func (s *Server) GetCache() *redis.Client { + return (s.handlers["cache"]).(*redis.Client) +} + +func (s *Server) GetDatabase() *pgxpool.Pool { // FIXME hardcoded index issue + return (s.handlers["database"]).(*pgxpool.Pool) +} + +// func (s *Server) GetEventBus() *amqp.Channel { +// return (s.handlers["eventbus"]).(*amqp.Channel) // } -func (s *Server) Shutdown() p.PurgeFn { - return func() error { - s.Logger.Log("Server %s is going down...", s.Base.AppID) +func (s *Server) GetLogger() *fluentd.Logger { + return (s.handlers["logger"]).(*fluentd.Logger) +} - // s.Registry.Unregister() - // s.clearMetadataCache() - s.Database.Close() - s.Logger.Log("Gone.") - s.Logger.Close() - - return s.Base.Shutdown() - } +func (s *Server) GetRegistry() *consul.Service { + return (s.handlers["registry"]).(*consul.Service) } // @CHECK: merge s.Config and s.Base.Config to display all config as one array/map -// func fetchKVConfig(s *Server) { // @FIXME: merge duplication in server.go and worker.go -// config, _, err := s.Registry.KV().Get(s.Config.KVNamespace, nil) -// if err != nil || config == nil { -// return -// } +// func (s *Server) registerKVUpdater() { // @FIXME: merge duplication in server.go and worker.go +// go func() { +// ticker := time.NewTicker(time.Second * 10) +// for range ticker.C { +// config, _, err := s.Registry.KV().Get(s.cnf.KVNamespace, nil) +// if err != nil || config == nil { +// return +// } -// kvCnf := bytes.NewBuffer(config.Value) -// decoder := json.NewDecoder(kvCnf) -// if err := decoder.Decode(&s.Config); err != nil { -// return -// } +// kvCnf := bytes.NewBuffer(config.Value) +// decoder := json.NewDecoder(kvCnf) +// if err := decoder.Decode(&s.cnf); err != nil { +// return +// } +// } +// }() // } -// func (s *Server) cacheMetadata() { -// ctx := context.Background() -// key, address := s.getMetadataIPsKey(), s.Base.Config.AppID +// // func (s *Server) clearMetadataCache() { +// // ctx := context.Background() +// // key, address := s.getMetadataIPsKey(), s.cnf.Base.AppID -// pos := s.Cache.LPos(ctx, key, address, redis.LPosArgs{}).Val() -// if pos >= 0 { -// s.Cache.LRem(ctx, key, 0, address) -// } +// // s.Cache.LRem(ctx, key, 0, address) +// // } -// s.Cache.LPush(ctx, key, address).Err() -// } - -// func (s *Server) clearMetadataCache() { -// ctx := context.Background() -// key, address := s.getMetadataIPsKey(), s.Config.Base.AppID - -// s.Cache.LRem(ctx, key, 0, address) -// } - -// func (s *Server) getMetadataIPsKey() string { -// return "internal__" + s.Base.Config.AppName + "__ips" -// } +// // func (s *Server) getMetadataIPsKey() string { +// // return "internal__" + s.cnf.Name + "__ips" +// // } diff --git a/src/internal/server/traefik_handler.go b/src/internal/server/traefik_handler.go index cdb6258..de0fa74 100644 --- a/src/internal/server/traefik_handler.go +++ b/src/internal/server/traefik_handler.go @@ -3,7 +3,7 @@ package server import ( "net/http" - "git.pbiernat.dev/egosport/identity-svc/internal/service" + "git.pbiernat.io/egommerce/identity-service/internal/service" "github.com/gofiber/fiber/v2" ) @@ -16,11 +16,11 @@ func (s *Server) TraefikHandler(c *fiber.Ctx) error { cookie := service.AuthService.Cookie("traefik", "dummy-traefik-token") c.Cookie(cookie) - s.Logger.Log("Traefik action set cookie. done.") + s.GetLogger().Log("Traefik action set cookie. done.") - c.Response().Header.Add("Server", "identity-svc/traefik") + c.Response().Header.Add("Server", "identity-service/traefik") reqCookie := c.Request().Header.Cookie("basket_id") - s.Logger.Log("Request cookie: %s", reqCookie) + s.GetLogger().Log("Request cookie: %s", reqCookie) return c. Status(http.StatusOK). diff --git a/src/internal/service/auth.go b/src/internal/service/auth.go index fdbf812..9fef02a 100644 --- a/src/internal/service/auth.go +++ b/src/internal/service/auth.go @@ -4,7 +4,7 @@ import ( "errors" "strconv" - "git.pbiernat.dev/egosport/identity-svc/pkg/config" + baseCnf "git.pbiernat.io/egommerce/go-api-pkg/config" "github.com/gofiber/fiber/v2" ) @@ -16,7 +16,7 @@ var ( ) func init() { - cookieExpireTime, _ := strconv.Atoi(config.GetEnv("AUTH_COOKIE_EXPIRE_TIME", "5")) + cookieExpireTime, _ := strconv.Atoi(baseCnf.GetEnv("AUTH_COOKIE_EXPIRE_TIME", "5")) AuthService = &Auth{"jwt_token", "jwt_token_refresh", cookieExpireTime} } diff --git a/src/internal/service/jwt.go b/src/internal/service/jwt.go index 628cfaf..a756fc9 100644 --- a/src/internal/service/jwt.go +++ b/src/internal/service/jwt.go @@ -5,7 +5,7 @@ import ( "strconv" "time" - "git.pbiernat.dev/egosport/identity-svc/pkg/config" + baseCnf "git.pbiernat.io/egommerce/go-api-pkg/config" "github.com/golang-jwt/jwt" ) @@ -15,8 +15,8 @@ var ( ) func init() { - tokenExpireTime, _ = strconv.Atoi(config.GetEnv("JWT_TOKEN_EXPIRE_TIME", "5")) - tokenSecret = []byte(config.GetEnv("JWT_SECRET_KEY", "B413IlIv9nKQfsMCXTE0Cteo4yHgUEfqaLfjg73sNlh")) // FIXME env: JWT_SECRET_KEY !!! + tokenExpireTime, _ = strconv.Atoi(baseCnf.GetEnv("JWT_TOKEN_EXPIRE_TIME", "5")) + tokenSecret = []byte(baseCnf.GetEnv("JWT_SECRET_KEY", "B413IlIv9nKQfsMCXTE0Cteo4yHgUEfqaLfjg73sNlh")) // FIXME env: JWT_SECRET_KEY !!! JWTService = &JWT{tokenExpireTime, tokenSecret} } diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go deleted file mode 100644 index 67c6b43..0000000 --- a/src/pkg/config/config.go +++ /dev/null @@ -1,22 +0,0 @@ -package config - -import ( - "os" - - "github.com/joho/godotenv" -) - -var ErrLoadingEnvs error - -func init() { - ErrLoadingEnvs = godotenv.Load() -} - -func GetEnv(name string, defVal string) string { - env := os.Getenv(name) - if env == "" { - return defVal - } - - return env -} diff --git a/src/pkg/server/config.go b/src/pkg/server/config.go deleted file mode 100644 index fca21d3..0000000 --- a/src/pkg/server/config.go +++ /dev/null @@ -1,21 +0,0 @@ -package server - -import ( - "fmt" - "time" -) - -type Config struct { - AppID string - AppName string - NetAddr string - PathPrefix string - - IdleTimeout time.Duration // miliseconds - ReadTimeout time.Duration // miliseconds - WriteTimeout time.Duration // miliseconds -} - -func (c *Config) GetAppFullName() string { - return fmt.Sprintf("%s_%s", c.AppName, c.AppID) -} diff --git a/src/pkg/server/server.go b/src/pkg/server/server.go deleted file mode 100644 index 057d6c3..0000000 --- a/src/pkg/server/server.go +++ /dev/null @@ -1,101 +0,0 @@ -package server - -import ( - "log" - "net" - "os" - "os/signal" - "strconv" - "syscall" - "time" - - "github.com/gofiber/fiber/v2" - - "git.pbiernat.dev/egommerce/api-entities/http" -) - -type ( - Server struct { - *fiber.App - *Config - - addr string // e.g. "127.0.0.1:8080" - - PurgeFn - } - HeaderRequestID struct { - RequestID string `reqHeader:"x-request-id"` - } - OptionFn func(*Server) error - PurgeFn func() error -) - -func New(conf *Config) *Server { - return &Server{ - App: fiber.New(fiber.Config{ - AppName: conf.AppID, - ServerHeader: conf.AppName + ":" + conf.AppID, - ReadTimeout: conf.ReadTimeout * time.Millisecond, - WriteTimeout: conf.WriteTimeout * time.Millisecond, - IdleTimeout: conf.IdleTimeout * time.Millisecond, - }), - Config: conf, - addr: conf.NetAddr, - } -} - -func (s *Server) Start(while chan struct{}) error { - go func() { - sigint := make(chan os.Signal, 1) - signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) - <-sigint - - if err := s.PurgeFn(); err != nil { - log.Fatalf("Failed to shutdown server. Reason: %v\n", err) - } - - close(while) - }() - - run := s.createRunFile("/app.run") // TODO move to common library (shared between server and worker) - defer s.removeRunFile(run) - - ln, _ := net.Listen("tcp", s.addr) - // ln = tls.NewListener(ln, s.App.Server().TLSConfig) - err := s.Listener(ln) - if err != nil { - log.Fatalf("Failed to start server: %s. Reason: %v\n", s.Config.AppID, err) - close(while) - } - <-while - - return err -} - -func (s *Server) GetRequestID(c *fiber.Ctx) (string, error) { - var hdr = new(HeaderRequestID) - if err := c.ReqHeaderParser(hdr); err != nil { - return "", err - } - - return hdr.RequestID, nil -} - -func (s *Server) Error(c *fiber.Ctx, code int, msg string) error { - return c.Status(code).JSON(http.ErrorResponse{Error: msg}) -} - -func (s *Server) createRunFile(path string) *os.File { - run, err := os.Create(path) - if err != nil { - log.Fatalf("Failed to create run file. Reason: %v\n", err) - os.Exit(1) - } - run.WriteString(strconv.Itoa(os.Getpid())) - - return run -} - -func (s *Server) removeRunFile(f *os.File) error { - return f.Close() -}