Skip to content

Commit 7f50108

Browse files
committed
Merge branch 'url-validate' into 'master'
Better URL validation See merge request joinimpact/api!85
2 parents 512c8d0 + aed2f4e commit 7f50108

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

internal/organizations/format.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package organizations
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
// formatURL takes a string with a user-inputted URL and returns a standardized, formatted URL which contains a protocol if one does not already exist.
9+
func formatURL(url string) string {
10+
if len(url) < 1 {
11+
return ""
12+
}
13+
14+
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
15+
return url
16+
}
17+
18+
return fmt.Sprintf("http://%s", url)
19+
}

internal/organizations/service.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ func (s *service) UpdateOrganizationProfile(organizationID int64, profile Organi
195195
},
196196
Name: profile.Name,
197197
Description: profile.Description,
198-
WebsiteURL: profile.WebsiteURL,
198+
WebsiteURL: formatURL(profile.WebsiteURL),
199199
})
200200
}
201201

pkg/parse/parse.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ func POST(w http.ResponseWriter, r *http.Request, s interface{}) error {
6060
validate := validator.New()
6161
validate.RegisterValidation("minAge", validators.MinAge)
6262
validate.RegisterValidation("maxAge", validators.MaxAge)
63+
validate.RegisterValidation("url", validators.URL)
6364

6465
err := validate.Struct(s)
6566
if err == nil {

pkg/validators/url.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package validators
2+
3+
import (
4+
"regexp"
5+
6+
"github.com/go-playground/validator/v10"
7+
)
8+
9+
const urlRegex = `^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$`
10+
11+
// URL validates a web URL.
12+
func URL(fl validator.FieldLevel) bool {
13+
if match, err := regexp.MatchString(urlRegex, fl.Field().Interface().(string)); !match || err != nil {
14+
return false
15+
}
16+
17+
return true
18+
}

0 commit comments

Comments
 (0)