Saturday 4 September 2021

Go Base64 Encoding

We can encode String and url in Go. Go has Encoder which takes byte array and convert into string encoding.

The Decoder takes the encoded value and covert it to the original string.

Go Base64 Example

  1. package main  
  2.   
  3. import "fmt"  
  4. import b64 "encoding/base64"  
  5. func main() {  
  6.     data := "DotNetTPoint@12345!@#$%^&*()"  
  7.     strEncode :=b64.StdEncoding.EncodeToString([]byte(data))  
  8.     fmt.Println("value to be encode  "+data)  
  9.     fmt.Println("Encoden value:  "+strEncode)  
  10.   
  11.     fmt.Println()  
  12.   
  13.   
  14.     fmt.Print("Value to be decode  "+strEncode)  
  15.     strDecode, _ := b64.StdEncoding.DecodeString(strEncode)  
  16.     fmt.Println("Decoded value  "+string( strDecode))  
  17.     fmt.Println()  
  18.   
  19.     url := "https://golang.org/ref/spec"  
  20.   
  21.     fmt.Println("url to be encode  "+url)  
  22.     urlEncode := b64.URLEncoding.EncodeToString([]byte(url))  
  23.     fmt.Println("Encoded url  "+urlEncode)  
  24.   
  25.     fmt.Println("value to be decode  "+urlEncode)  
  26.     strDecode2,_ := b64.URLEncoding.DecodeString(urlEncode)  
  27.   
  28.     fmt.Println("Decoded value  "+string(strDecode2))  
  29. }  

Output:

value to be encode  DotNetTPoint@12345!@#$%^&*()
Encoden value:  SmF2YVRwb2ludEAxMjM0NSFAIyQlXiYqKCk=

Value to be decode  SmF2YVRwb2ludEAxMjM0NSFAIyQlXiYqKCk=Decoded value  Ja-vaTpoint@12345!@#$%^&*()

url to be encode  https://golang.org/ref/spec
Encoded url  aHR0cHM6Ly9nb2xhbmcub3JnL3JlZi9zcGVj
value to be decode  aHR0cHM6Ly9nb2xhbmcub3JnL3JlZi9zcGVj
Decoded value  https://golang.org/ref/spec

Process finished with exit code 0

No comments:

Post a Comment