Skip to content

Commit 7fd735c

Browse files
author
Christian Roessner
committed
Add octal_mode validation for Mode field
Introduced a new custom validation rule, "octal_mode," for the Mode field in configurations. This ensures that the field contains valid octal values, enhancing input validation and preventing misconfiguration.
1 parent 7fbf3ae commit 7fd735c

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

config.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"errors"
55
"fmt"
66
"log/slog"
7+
"strconv"
78
"strings"
89
"time"
910
"unicode"
@@ -33,7 +34,7 @@ type Listen struct {
3334
Type string `mapstructure:"type" validate:"required,oneof=tcp tcp6 unix"`
3435
Address string `mapstructure:"address" validate:"required,ip_addr|filepath"`
3536
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
36-
Mode string `mapstructure:"mode" validate:"omitempty,min=4,max=5,alphanumunicode"`
37+
Mode string `mapstructure:"mode" validate:"omitempty,octal_mode"`
3738
}
3839

3940
type Logging struct {
@@ -76,6 +77,8 @@ func (cfg *Config) HandleConfig() error {
7677

7778
validate := validator.New(validator.WithRequiredStructEnabled())
7879

80+
_ = validate.RegisterValidation("octal_mode", isValidOctalMode)
81+
7982
err = validate.Struct(cfg)
8083
if err == nil {
8184
return nil
@@ -138,6 +141,18 @@ func NewConfigFile() (cfg *Config, err error) {
138141
return cfg, err
139142
}
140143

144+
func isValidOctalMode(fl validator.FieldLevel) bool {
145+
mode := fl.Field().String()
146+
147+
if !strings.HasPrefix(mode, "0") {
148+
return false
149+
}
150+
151+
_, err := strconv.ParseUint(mode, 8, 32)
152+
153+
return err == nil
154+
}
155+
141156
func toSnakeCase(fieldName string) string {
142157
var result strings.Builder
143158

0 commit comments

Comments
 (0)