refactor: replace magic values with constants

This commit is contained in:
Michael
2026-04-29 23:24:19 +02:00
parent d396cad6f3
commit 8909b82e66
2 changed files with 35 additions and 7 deletions

View File

@ -2,24 +2,30 @@ package url
import (
neturl "net/url"
"git.heldm.com/held/qrcode/internal/qrcode/vo"
)
func IsValidURL(newURL string) bool {
if newURL == "" || len(newURL) > 2048 {
return false
}
u, err := neturl.Parse(newURL)
if err != nil {
return false
}
if u.Scheme == "" || u.Host == "" {
return false
}
switch u.Scheme {
case "http", "https", "ftp", "ftps", "mailto":
case vo.SchemeHTTP, vo.SchemeHTTPS, vo.SchemeFTP, vo.SchemeFTPS, vo.SchemeMAILTO:
break
default:
return false
}
return true
}

View File

@ -7,6 +7,23 @@ import (
"git.heldm.com/held/qrcode/internal/qrcode"
)
const (
SchemeHTTP = "http"
SchemeHTTPS = "https"
SchemeFTP = "ftp"
SchemeFTPS = "ftps"
SchemeMAILTO = "mailto"
ImgFormatPNG = "png"
ImgFormatSVG = "svg"
ImgDefaultFormat = ImgFormatPNG
ImgMinSize = 256
ImgMaxSize = 2048
ImgDefaultSize = 256
)
type QRImg struct {
link string
img []byte
@ -27,23 +44,28 @@ func NewQR(link, imgFormat string, imgSize int) (*QRImg, error) {
return nil, qrcode.ErrInvalidURL
}
if u.Scheme != "http" && u.Scheme != "https" {
if u.Scheme != SchemeHTTP &&
u.Scheme != SchemeHTTPS &&
u.Scheme != SchemeFTP &&
u.Scheme != SchemeFTPS &&
u.Scheme != SchemeMAILTO {
return nil, qrcode.ErrInvalidURL
}
// imgFormat should be either "png" or "svg", default to "png" if invalid
switch imgFormat {
case "png", "svg":
case ImgFormatPNG, ImgFormatSVG:
default:
imgFormat = "png"
imgFormat = ImgDefaultFormat
}
// imgSize should be between 256 and 2048, default to 256 if invalid
if imgSize <= 0 {
imgSize = 256
imgSize = ImgDefaultSize
}
if imgSize > 2048 {
imgSize = 2048
if imgSize > ImgMaxSize {
imgSize = ImgMaxSize
}
return &QRImg{