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"
)
// 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"`
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

View File

@@ -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)
}
}

View File

@@ -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)

View File

@@ -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,16 +84,13 @@ 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 {
} 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))
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)
if err != nil {
return "", 0, err
}