Golang net/url.Userinfo type, Password() and Username() functions example

package net/url

Golang net/url.Userinfo type, Password() and Username() functions usage example

 package main

 import (
  "fmt"
  "net/url"
 )

 func main() {

  // username and password must be in plain text (see below)
  rawURL := "http://username:password@example.com"

  parsedURL, err := url.Parse(rawURL)
  if err != nil {
 panic(err)
  }

  if parsedURL.User != nil {
 user := parsedURL.User
 fmt.Println(user.Username())

 // otherwise this will print out password minus the "weird" characters
 pw, isset := user.Password()

 fmt.Println(pw)
 fmt.Println("Is set? : ", isset)

  } else {
 fmt.Println("No username or password found")
  }

 }

Output :

username

password

Is set? : true

References :

http://golang.org/pkg/net/url/#Userinfo

http://golang.org/pkg/net/url/#Userinfo.Password

http://golang.org/pkg/net/url/#Userinfo.Username

Advertisement