Code style improvements

This commit is contained in:
Jacob Gunther
2023-03-30 15:45:39 -05:00
parent 3c83c64f1a
commit 5841ad9803
4 changed files with 39 additions and 54 deletions

View File

@@ -9,25 +9,23 @@ import (
"gopkg.in/yaml.v3" "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. // Config represents the application configuration.
type Config struct { type Config struct {
Environment string `yaml:"environment"` Environment string `yaml:"environment"`
Host string `yaml:"host"` Host string `yaml:"host"`
Port uint16 `yaml:"port"` Port uint16 `yaml:"port"`
Redis *string `yaml:"redis"` Redis *string `yaml:"redis"`
Cache CacheConfig `yaml:"cache"` 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. // ReadFile reads the configuration from the given file and overrides values using environment variables.
func (c *Config) ReadFile(file string) error { func (c *Config) ReadFile(file string) error {
data, err := os.ReadFile(file) data, err := os.ReadFile(file)
if err != nil { if err != nil {
return err return err
} }
@@ -41,23 +39,26 @@ func (c *Config) ReadFile(file string) error {
// overrideWithEnvVars overrides configuration values using environment variables. // overrideWithEnvVars overrides configuration values using environment variables.
func (c *Config) overrideWithEnvVars() error { func (c *Config) overrideWithEnvVars() error {
if env := os.Getenv("ENVIRONMENT"); env != "" { if value := os.Getenv("ENVIRONMENT"); value != "" {
c.Environment = env c.Environment = value
} }
if host := os.Getenv("HOST"); host != "" { if value := os.Getenv("HOST"); value != "" {
c.Host = host c.Host = value
} }
if port := os.Getenv("PORT"); port != "" { if value := os.Getenv("PORT"); value != "" {
portInt, err := strconv.Atoi(port) portInt, err := strconv.Atoi(value)
if err != nil { if err != nil {
return errors.New("invalid port value in environment variable") return errors.New("invalid port value in environment variable")
} }
c.Port = uint16(portInt) 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 return nil

View File

@@ -16,6 +16,7 @@ var (
DisableStartupMessage: true, DisableStartupMessage: true,
ErrorHandler: func(ctx *fiber.Ctx, err error) error { ErrorHandler: func(ctx *fiber.Ctx, err error) error {
log.Printf("Error: %v - URI: %v\n", err, ctx.Request().URI()) log.Printf("Error: %v - URI: %v\n", err, ctx.Request().URI())
return ctx.SendStatus(http.StatusInternalServerError) return ctx.SendStatus(http.StatusInternalServerError)
}, },
}) })
@@ -24,26 +25,24 @@ var (
) )
func init() { func init() {
// Read config file
if err := config.ReadFile("config.yml"); err != nil { 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 { 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") log.Println("Successfully retrieved EULA blocked servers")
// Connect to Redis if the config is set
if config.Redis != nil { if config.Redis != nil {
if err := r.Connect(); err != 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") log.Println("Successfully connected to Redis")
} }
// Set up middleware
app.Use(recover.New(recover.Config{ app.Use(recover.New(recover.Config{
EnableStackTrace: true, EnableStackTrace: true,
})) }))
@@ -66,7 +65,8 @@ func main() {
defer r.Close() defer r.Close()
log.Printf("Listening on %s:%d\n", config.Host, config.Port) 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 { 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)
} }
} }

View File

@@ -10,7 +10,6 @@ import (
func init() { func init() {
app.Get("/ping", PingHandler) app.Get("/ping", PingHandler)
app.Get("/statistics", StatisticsHandler)
app.Get("/status/java/:address", JavaStatusHandler) app.Get("/status/java/:address", JavaStatusHandler)
app.Get("/status/bedrock/:address", BedrockStatusHandler) app.Get("/status/bedrock/:address", BedrockStatusHandler)
app.Get("/icon", DefaultIconHandler) app.Get("/icon", DefaultIconHandler)
@@ -18,23 +17,11 @@ func init() {
app.Use(NotFoundHandler) 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. // PingHandler responds with a 200 OK status for simple health checks.
func PingHandler(ctx *fiber.Ctx) error { func PingHandler(ctx *fiber.Ctx) error {
return ctx.SendStatus(http.StatusOK) 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. // JavaStatusHandler returns the status of the Java edition Minecraft server specified in the address parameter.
func JavaStatusHandler(ctx *fiber.Ctx) error { func JavaStatusHandler(ctx *fiber.Ctx) error {
host, port, err := ParseAddress(ctx.Params("address"), 25565) host, port, err := ParseAddress(ctx.Params("address"), 25565)

View File

@@ -40,11 +40,10 @@ func (m *MutexArray) Has(value interface{}) bool {
return false return false
} }
// GetBlockedServerList fetches the list of blocked servers from Mojang's session server. // GetBlockedServerList fetches the list of blocked servers from Mojang's session server.
func GetBlockedServerList() error { func GetBlockedServerList() error {
resp, err := http.Get("https://sessionserver.mojang.com/blockedservers") resp, err := http.Get("https://sessionserver.mojang.com/blockedservers")
if err != nil { if err != nil {
return err return err
} }
@@ -56,6 +55,7 @@ func GetBlockedServerList() error {
defer resp.Body.Close() defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }
@@ -63,6 +63,7 @@ func GetBlockedServerList() error {
// Convert []string to []interface{} // Convert []string to []interface{}
strSlice := strings.Split(string(body), "\n") strSlice := strings.Split(string(body), "\n")
interfaceSlice := make([]interface{}, len(strSlice)) interfaceSlice := make([]interface{}, len(strSlice))
for i, v := range strSlice { for i, v := range strSlice {
interfaceSlice[i] = v interfaceSlice[i] = v
} }
@@ -75,8 +76,6 @@ func GetBlockedServerList() error {
return nil return nil
} }
// IsBlockedAddress checks if the given address is in the blocked servers list. // IsBlockedAddress checks if the given address is in the blocked servers list.
func IsBlockedAddress(address string) bool { func IsBlockedAddress(address string) bool {
split := strings.Split(strings.ToLower(address), ".") split := strings.Split(strings.ToLower(address), ".")
@@ -85,16 +84,13 @@ func IsBlockedAddress(address string) bool {
for k := range split { for k := range split {
var newAddress string var newAddress string
switch k { if k == 0 {
case 0:
newAddress = strings.Join(split, ".") newAddress = strings.Join(split, ".")
default: } else if isIPAddress {
if isIPAddress {
newAddress = fmt.Sprintf("%s.*", strings.Join(split[0:len(split)-k], ".")) newAddress = fmt.Sprintf("%s.*", strings.Join(split[0:len(split)-k], "."))
} else { } else {
newAddress = fmt.Sprintf("*.%s", strings.Join(split[k:], ".")) newAddress = fmt.Sprintf("*.%s", strings.Join(split[k:], "."))
} }
}
newAddressBytes := sha1.Sum([]byte(newAddress)) newAddressBytes := sha1.Sum([]byte(newAddress))
newAddressHash := hex.EncodeToString(newAddressBytes[:]) newAddressHash := hex.EncodeToString(newAddressBytes[:])
@@ -120,6 +116,7 @@ func ParseAddress(address string, defaultPort uint16) (string, uint16, error) {
} }
port, err := strconv.ParseUint(result[1], 10, 16) port, err := strconv.ParseUint(result[1], 10, 16)
if err != nil { if err != nil {
return "", 0, err return "", 0, err
} }