Update validation package to work with generation.Parameters type

This commit is contained in:
Fred Boniface 2023-09-02 21:04:29 +01:00
parent cc08f8358e
commit d3bd2673e8
2 changed files with 13 additions and 9 deletions

View File

@ -1,29 +1,33 @@
package validation package validation
import "fmt" import (
"fmt"
func Validate(input string, format string) bool { "git.fjla.uk/fred.boniface/barcodes/generation"
rule, exists := FormatRules[format] )
func Validate(params generation.Parameters) bool {
rule, exists := FormatRules[string(params.Format)]
if !exists { if !exists {
fmt.Printf("Error: No rule found for format '%s'\n", format) fmt.Printf("Error: No rule found for format '%s'\n", params.Format)
return false return false
} }
if uint64(len(input)) < rule.minLength || uint64(len(input)) > rule.maxLength { if uint64(len(params.Content)) < rule.minLength || uint64(len(params.Content)) > rule.maxLength {
fmt.Printf("Validation Error: Length must be between %d and %d\n", rule.minLength, rule.maxLength) fmt.Printf("Validation Error: Length must be between %d and %d\n", rule.minLength, rule.maxLength)
return false return false
} }
if !rule.charset.MatchString(input) { if !rule.charset.MatchString(params.Content) {
fmt.Println("Validation Error: Contains illegal characters") fmt.Println("Validation Error: Contains illegal characters")
return false return false
} }
if uint64(len(input))%uint64(rule.divisible) != 0 { if uint64(len(params.Content))%uint64(rule.divisible) != 0 {
fmt.Printf("Validation Error: Length must be a multiple of %d", rule.divisible) fmt.Printf("Validation Error: Length must be a multiple of %d", rule.divisible)
return false return false
} }
fmt.Printf("Validation passed for barcode type %s\n", format) fmt.Printf("Validation passed for barcode type %s\n", params.Format)
return true return true
} }

View File

@ -26,7 +26,7 @@ func generateBarcode(w http.ResponseWriter, r *http.Request) {
Content: req.Content, Content: req.Content,
} }
validate := validation.Validate(req.Content, req.BarcodeType) validate := validation.Validate(parameters)
if !validate { if !validate {
fmt.Println("Validation Failed") fmt.Println("Validation Failed")
http.Error(w, "Validation Failed", http.StatusBadRequest) http.Error(w, "Validation Failed", http.StatusBadRequest)