From 5841ad9803cef7491007d8fc3ee709abfe631d7f Mon Sep 17 00:00:00 2001 From: Jacob Gunther Date: Thu, 30 Mar 2023 15:45:39 -0500 Subject: [PATCH] Code style improvements --- src/config.go | 41 +++++++++++++++++++++-------------------- src/main.go | 16 ++++++++-------- src/routes.go | 13 ------------- src/util.go | 23 ++++++++++------------- 4 files changed, 39 insertions(+), 54 deletions(-) diff --git a/src/config.go b/src/config.go index bfd70db..c2f0483 100644 --- a/src/config.go +++ b/src/config.go @@ -9,25 +9,23 @@ import ( "gopkg.in/yaml.v3" ) -// CacheConfig contains cache-related settings. -type CacheConfig struct { - JavaStatusDuration time.Duration `yaml:"java_status_duration" json:"java_status_duration"` - BedrockStatusDuration time.Duration `yaml:"bedrock_status_duration" json:"bedrock_status_duration"` - IconDuration time.Duration `yaml:"icon_duration" json:"icon_duration"` -} - // Config represents the application configuration. type Config struct { - Environment string `yaml:"environment"` - Host string `yaml:"host"` - Port uint16 `yaml:"port"` - Redis *string `yaml:"redis"` - Cache CacheConfig `yaml:"cache"` + Environment string `yaml:"environment"` + Host string `yaml:"host"` + Port uint16 `yaml:"port"` + Redis *string `yaml:"redis"` + Cache struct { + JavaStatusDuration time.Duration `yaml:"java_status_duration" json:"java_status_duration"` + BedrockStatusDuration time.Duration `yaml:"bedrock_status_duration" json:"bedrock_status_duration"` + IconDuration time.Duration `yaml:"icon_duration" json:"icon_duration"` + } `yaml:"cache"` } // 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) + if err != nil { return err } @@ -41,23 +39,26 @@ func (c *Config) ReadFile(file string) error { // overrideWithEnvVars overrides configuration values using environment variables. func (c *Config) overrideWithEnvVars() error { - if env := os.Getenv("ENVIRONMENT"); env != "" { - c.Environment = env + if value := os.Getenv("ENVIRONMENT"); value != "" { + c.Environment = value } - if host := os.Getenv("HOST"); host != "" { - c.Host = host + if value := os.Getenv("HOST"); value != "" { + c.Host = value } - if port := os.Getenv("PORT"); port != "" { - portInt, err := strconv.Atoi(port) + if value := os.Getenv("PORT"); value != "" { + portInt, err := strconv.Atoi(value) + if err != nil { return errors.New("invalid port value in environment variable") } + c.Port = uint16(portInt) } - if redisURL := os.Getenv("REDIS_URL"); redisURL != "" { - c.Redis = &redisURL + + if value := os.Getenv("REDIS_URL"); value != "" { + c.Redis = &value } return nil diff --git a/src/main.go b/src/main.go index e48f58b..2ce8059 100644 --- a/src/main.go +++ b/src/main.go @@ -16,6 +16,7 @@ var ( DisableStartupMessage: true, ErrorHandler: func(ctx *fiber.Ctx, err error) error { log.Printf("Error: %v - URI: %v\n", err, ctx.Request().URI()) + return ctx.SendStatus(http.StatusInternalServerError) }, }) @@ -24,26 +25,24 @@ var ( ) func init() { - // Read config file if err := config.ReadFile("config.yml"); err != nil { - log.Fatalf("Failed to read config file: %v", err) + log.Fatalf("failed to read config file: %v", err) } - // Get the blocked server list if err := GetBlockedServerList(); err != nil { - log.Fatalf("Failed to retrieve EULA blocked servers: %v", err) + log.Fatalf("failed to retrieve EULA blocked servers: %v", err) } + log.Println("Successfully retrieved EULA blocked servers") - // Connect to Redis if the config is set if config.Redis != nil { if err := r.Connect(); err != nil { - log.Fatalf("Failed to connect to Redis: %v", err) + log.Fatalf("failed to connect to Redis: %v", err) } + log.Println("Successfully connected to Redis") } - // Set up middleware app.Use(recover.New(recover.Config{ EnableStackTrace: true, })) @@ -66,7 +65,8 @@ func main() { defer r.Close() log.Printf("Listening on %s:%d\n", config.Host, config.Port) + if err := app.Listen(fmt.Sprintf("%s:%d", config.Host, config.Port)); err != nil { - log.Fatalf("Failed to start server: %v", err) + log.Fatalf("failed to start server: %v", err) } } diff --git a/src/routes.go b/src/routes.go index 84df19c..2ff7cf0 100644 --- a/src/routes.go +++ b/src/routes.go @@ -10,7 +10,6 @@ import ( func init() { app.Get("/ping", PingHandler) - app.Get("/statistics", StatisticsHandler) app.Get("/status/java/:address", JavaStatusHandler) app.Get("/status/bedrock/:address", BedrockStatusHandler) app.Get("/icon", DefaultIconHandler) @@ -18,23 +17,11 @@ func init() { app.Use(NotFoundHandler) } -// StatisticsResponse is the structure for the response of the statistics route. -type StatisticsResponse struct { - Cache CacheConfig `json:"cache"` -} - // PingHandler responds with a 200 OK status for simple health checks. func PingHandler(ctx *fiber.Ctx) error { return ctx.SendStatus(http.StatusOK) } -// StatisticsHandler returns the cache configuration in the response. -func StatisticsHandler(ctx *fiber.Ctx) error { - return ctx.JSON(StatisticsResponse{ - Cache: config.Cache, - }) -} - // JavaStatusHandler returns the status of the Java edition Minecraft server specified in the address parameter. func JavaStatusHandler(ctx *fiber.Ctx) error { host, port, err := ParseAddress(ctx.Params("address"), 25565) diff --git a/src/util.go b/src/util.go index 72dae8d..c5c8297 100644 --- a/src/util.go +++ b/src/util.go @@ -16,7 +16,7 @@ import ( var ( //go:embed icon.png defaultIcon []byte - blockedServers *MutexArray = nil + blockedServers *MutexArray = nil ipAddressRegex *regexp.Regexp = regexp.MustCompile(`^\d{1,3}(\.\d{1,3}){3}$`) ) @@ -40,11 +40,10 @@ func (m *MutexArray) Has(value interface{}) bool { return false } - - // GetBlockedServerList fetches the list of blocked servers from Mojang's session server. func GetBlockedServerList() error { resp, err := http.Get("https://sessionserver.mojang.com/blockedservers") + if err != nil { return err } @@ -56,6 +55,7 @@ func GetBlockedServerList() error { defer resp.Body.Close() body, err := io.ReadAll(resp.Body) + if err != nil { return err } @@ -63,6 +63,7 @@ func GetBlockedServerList() error { // Convert []string to []interface{} strSlice := strings.Split(string(body), "\n") interfaceSlice := make([]interface{}, len(strSlice)) + for i, v := range strSlice { interfaceSlice[i] = v } @@ -75,8 +76,6 @@ func GetBlockedServerList() error { return nil } - - // IsBlockedAddress checks if the given address is in the blocked servers list. func IsBlockedAddress(address string) bool { split := strings.Split(strings.ToLower(address), ".") @@ -85,15 +84,12 @@ func IsBlockedAddress(address string) bool { for k := range split { var newAddress string - switch k { - case 0: + if k == 0 { newAddress = strings.Join(split, ".") - default: - if isIPAddress { - newAddress = fmt.Sprintf("%s.*", strings.Join(split[0:len(split)-k], ".")) - } else { - newAddress = fmt.Sprintf("*.%s", strings.Join(split[k:], ".")) - } + } else if isIPAddress { + newAddress = fmt.Sprintf("%s.*", strings.Join(split[0:len(split)-k], ".")) + } else { + newAddress = fmt.Sprintf("*.%s", strings.Join(split[k:], ".")) } newAddressBytes := sha1.Sum([]byte(newAddress)) @@ -120,6 +116,7 @@ func ParseAddress(address string, defaultPort uint16) (string, uint16, error) { } port, err := strconv.ParseUint(result[1], 10, 16) + if err != nil { return "", 0, err }