Skip to content

Instantly share code, notes, and snippets.

@kkohrt
Created April 26, 2021 04:28
Show Gist options
  • Save kkohrt/65f6e8656b0a7810db7bb6394595f849 to your computer and use it in GitHub Desktop.
Save kkohrt/65f6e8656b0a7810db7bb6394595f849 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/url"
"os"
)
// The URL library parse function https://golang.org/pkg/net/url/#Parse
// silently fails to parse a URL that does not include a scheme
// This means that you are turned a paritally formed or ill-formed URL object
// => If you include a port number, your domain will be assigned to scheme
// => If you include only a path, your domain/path will all be considered path
// => In all cases, hostname is left blank
/* Testing how AUTHN_URL is parsed, run these:
AUTHN_URL=host.domain.com go run urlparse.go
AUTHN_URL=host.domain.com:2112 go run urlparse.go
AUTHN_URL=host.domain.com:2112/syrinx go run urlparse.go
AUTHN_URL=host.domain.com/syrinx go run urlparse.go
AUTHN_URL=https://host.domain.com go run urlparse.go
AUTHN_URL=http://host.domain.com:2112/syrinx go run urlparse.go
*/
// Note that if you change to using "ParseRequestURI",
// you will get an error when parsing
func lookupURL(name string) (*url.URL, error) {
if val, ok := os.LookupEnv(name); ok {
return url.Parse(val)
}
return nil, nil
}
func readenv(name string) (string) {
if val, ok := os.LookupEnv(name); ok {
return val
}
return ""
}
func main() {
fmt.Printf("\nUnparsed URL from ENV: %s\n", readenv("AUTHN_URL"))
parsedURL, err := lookupURL("AUTHN_URL")
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Parsed URL Scheme : %s\n", parsedURL.Scheme)
fmt.Printf("Parsed URL Hostname : %s\n", parsedURL.Hostname())
fmt.Printf("Parsed URL Port : %s\n", parsedURL.Port())
fmt.Printf("parsed URL Path : %s\n", parsedURL.EscapedPath())
fmt.Printf("parsed URL as string : %s\n\n", parsedURL.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment