chore: declare explicit configs

This commit is contained in:
Reinaldy Rafli 2022-12-03 08:51:51 +07:00
parent f75e545bc5
commit 7dec072679
Signed by: aldy505
GPG Key ID: 1DAB793F100A560A
1 changed files with 182 additions and 170 deletions

View File

@ -1,170 +1,182 @@
package main package main
import ( import (
"errors" "errors"
"log" "log"
"net" "net"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
"context" "context"
"jokes-bapak2-api/core/joke" "jokes-bapak2-api/core/joke"
"jokes-bapak2-api/routes" "jokes-bapak2-api/routes"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/credentials"
"time" "time"
"github.com/allegro/bigcache/v3" "github.com/allegro/bigcache/v3"
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/rs/cors" "github.com/rs/cors"
) )
func main() { func main() {
redisURL, ok := os.LookupEnv("REDIS_URL") redisURL, ok := os.LookupEnv("REDIS_URL")
if !ok { if !ok {
redisURL = "redis://@localhost:6379" redisURL = "redis://@localhost:6379"
} }
minioHost, ok := os.LookupEnv("MINIO_HOST") minioHost, ok := os.LookupEnv("MINIO_HOST")
if !ok { if !ok {
minioHost = "localhost:9000" minioHost = "localhost:9000"
} }
minioID, ok := os.LookupEnv("MINIO_ACCESS_ID") minioRegion, ok := os.LookupEnv("MINIO_REGION")
if !ok { if !ok {
minioID = "minio" minioRegion = ""
} }
minioSecret, ok := os.LookupEnv("MINIO_SECRET_KEY") minioSecure, ok := os.LookupEnv("MINIO_SECURE")
if !ok { if !ok {
minioSecret = "password" minioSecure = "false"
} }
minioToken, ok := os.LookupEnv("MINIO_TOKEN") minioID, ok := os.LookupEnv("MINIO_ACCESS_ID")
if !ok { if !ok {
minioToken = "" minioID = "minio"
} }
sentryDsn, ok := os.LookupEnv("SENTRY_DSN") minioSecret, ok := os.LookupEnv("MINIO_SECRET_KEY")
if !ok { if !ok {
sentryDsn = "" minioSecret = "password"
} }
port, ok := os.LookupEnv("PORT") minioToken, ok := os.LookupEnv("MINIO_TOKEN")
if !ok { if !ok {
port = "5000" minioToken = ""
} }
hostname, ok := os.LookupEnv("HOSTNAME") sentryDsn, ok := os.LookupEnv("SENTRY_DSN")
if !ok { if !ok {
hostname = "127.0.0.1" sentryDsn = ""
} }
environment, ok := os.LookupEnv("ENVIRONMENT") port, ok := os.LookupEnv("PORT")
if !ok { if !ok {
environment = "development" port = "5000"
} }
// Setup In Memory hostname, ok := os.LookupEnv("HOSTNAME")
memory, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute)) if !ok {
if err != nil { hostname = "127.0.0.1"
log.Panicln(err) }
}
defer memory.Close() environment, ok := os.LookupEnv("ENVIRONMENT")
if !ok {
// Setup MinIO environment = "development"
minioClient, err := minio.New(minioHost, &minio.Options{ }
Creds: credentials.NewStaticV4(minioID, minioSecret, minioToken),
}) // Setup In Memory
if err != nil { memory, err := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
log.Fatalf("setting up minio client: %s", err.Error()) if err != nil {
return log.Panicln(err)
} }
defer memory.Close()
parsedRedisURL, err := redis.ParseURL(redisURL)
if err != nil { // Setup MinIO
log.Fatalf("parsing redis url: %s", err.Error()) minioClient, err := minio.New(minioHost, &minio.Options{
return Creds: credentials.NewStaticV4(minioID, minioSecret, minioToken),
} Region: minioRegion,
Secure: minioSecure == "true",
redisClient := redis.NewClient(parsedRedisURL) })
defer func() { if err != nil {
err := redisClient.Close() log.Fatalf("setting up minio client: %s", err.Error())
if err != nil { return
log.Printf("closing redis client: %s", err.Error()) }
}
}() parsedRedisURL, err := redis.ParseURL(redisURL)
if err != nil {
// Setup Sentry log.Fatalf("parsing redis url: %s", err.Error())
err = sentry.Init(sentry.ClientOptions{ return
Dsn: sentryDsn, }
Environment: environment,
AttachStacktrace: true, redisClient := redis.NewClient(parsedRedisURL)
// Enable printing of SDK debug messages. defer func() {
// Useful when getting started or trying to figure something out. err := redisClient.Close()
Debug: environment != "production", if err != nil {
}) log.Printf("closing redis client: %s", err.Error())
if err != nil { }
log.Fatalf("setting up sentry: %s", err.Error()) }()
return
} // Setup Sentry
defer sentry.Flush(2 * time.Second) err = sentry.Init(sentry.ClientOptions{
Dsn: sentryDsn,
setupCtx, setupCancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute*4)) Environment: environment,
defer setupCancel() AttachStacktrace: true,
// Enable printing of SDK debug messages.
_, _, err = joke.GetTodaysJoke(setupCtx, minioClient, redisClient, memory) // Useful when getting started or trying to figure something out.
if err != nil { Debug: environment != "production",
log.Fatalf("getting initial joke data: %s", err.Error()) })
return if err != nil {
} log.Fatalf("setting up sentry: %s", err.Error())
return
healthRouter := routes.Health(minioClient, redisClient) }
jokeRouter := routes.Joke(minioClient, redisClient, memory) defer sentry.Flush(2 * time.Second)
router := chi.NewRouter() setupCtx, setupCancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute*4))
defer setupCancel()
router.Use(cors.New(cors.Options{
AllowedMethods: []string{http.MethodGet}, _, _, err = joke.GetTodaysJoke(setupCtx, minioClient, redisClient, memory)
AllowCredentials: false, if err != nil {
MaxAge: int(60 * 60 * 24 * 365), log.Fatalf("getting initial joke data: %s", err.Error())
Debug: false, return
}).Handler) }
router.Mount("/health", healthRouter) healthRouter := routes.Health(minioClient, redisClient)
router.Mount("/", jokeRouter) jokeRouter := routes.Joke(minioClient, redisClient, memory)
server := &http.Server{ router := chi.NewRouter()
Handler: router,
Addr: net.JoinHostPort(hostname, port), router.Use(cors.New(cors.Options{
ReadTimeout: time.Minute, AllowedMethods: []string{http.MethodGet},
WriteTimeout: time.Minute, AllowCredentials: false,
IdleTimeout: time.Second * 30, MaxAge: int(60 * 60 * 24 * 365),
ReadHeaderTimeout: time.Minute, Debug: false,
} }).Handler)
exitSignal := make(chan os.Signal, 1) router.Mount("/health", healthRouter)
signal.Notify(exitSignal, os.Interrupt) router.Mount("/", jokeRouter)
go func() { server := &http.Server{
err := server.ListenAndServe() Handler: router,
if err != nil && !errors.Is(err, http.ErrServerClosed) { Addr: net.JoinHostPort(hostname, port),
log.Fatalf("listening http server: %v", err) ReadTimeout: time.Minute,
} WriteTimeout: time.Minute,
}() IdleTimeout: time.Second * 30,
ReadHeaderTimeout: time.Minute,
<-exitSignal }
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*30) exitSignal := make(chan os.Signal, 1)
defer shutdownCancel() signal.Notify(exitSignal, os.Interrupt)
err = server.Shutdown(shutdownCtx) go func() {
if err != nil { err := server.ListenAndServe()
log.Printf("shutting down http server: %v", err) if err != nil && !errors.Is(err, http.ErrServerClosed) {
} log.Fatalf("listening http server: %v", err)
} }
}()
<-exitSignal
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*30)
defer shutdownCancel()
err = server.Shutdown(shutdownCtx)
if err != nil {
log.Printf("shutting down http server: %v", err)
}
}