refactor: replace magic values with constants
This commit is contained in:
@ -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
|
||||
}
|
||||
|
||||
@ -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{
|
||||
|
||||
Reference in New Issue
Block a user