...

Source file src/github.com/go-openapi/jsonreference/internal/normalize_url.go

Documentation: github.com/go-openapi/jsonreference/internal

     1  package internal
     2  
     3  import (
     4  	"net/url"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  const (
    10  	defaultHTTPPort  = ":80"
    11  	defaultHTTPSPort = ":443"
    12  )
    13  
    14  // Regular expressions used by the normalizations
    15  var rxPort = regexp.MustCompile(`(:\d+)/?$`)
    16  var rxDupSlashes = regexp.MustCompile(`/{2,}`)
    17  
    18  // NormalizeURL will normalize the specified URL
    19  // This was added to replace a previous call to the no longer maintained purell library:
    20  // The call that was used looked like the following:
    21  //
    22  //	url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes))
    23  //
    24  // To explain all that was included in the call above, purell.FlagsSafe was really just the following:
    25  //   - FlagLowercaseScheme
    26  //   - FlagLowercaseHost
    27  //   - FlagRemoveDefaultPort
    28  //   - FlagRemoveDuplicateSlashes (and this was mixed in with the |)
    29  //
    30  // This also normalizes the URL into its urlencoded form by removing RawPath and RawFragment.
    31  func NormalizeURL(u *url.URL) {
    32  	lowercaseScheme(u)
    33  	lowercaseHost(u)
    34  	removeDefaultPort(u)
    35  	removeDuplicateSlashes(u)
    36  
    37  	u.RawPath = ""
    38  	u.RawFragment = ""
    39  }
    40  
    41  func lowercaseScheme(u *url.URL) {
    42  	if len(u.Scheme) > 0 {
    43  		u.Scheme = strings.ToLower(u.Scheme)
    44  	}
    45  }
    46  
    47  func lowercaseHost(u *url.URL) {
    48  	if len(u.Host) > 0 {
    49  		u.Host = strings.ToLower(u.Host)
    50  	}
    51  }
    52  
    53  func removeDefaultPort(u *url.URL) {
    54  	if len(u.Host) > 0 {
    55  		scheme := strings.ToLower(u.Scheme)
    56  		u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string {
    57  			if (scheme == "http" && val == defaultHTTPPort) || (scheme == "https" && val == defaultHTTPSPort) {
    58  				return ""
    59  			}
    60  			return val
    61  		})
    62  	}
    63  }
    64  
    65  func removeDuplicateSlashes(u *url.URL) {
    66  	if len(u.Path) > 0 {
    67  		u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/")
    68  	}
    69  }
    70  

View as plain text