In this source code example, we will demonstrate how to use base64.URLEncoding to encode and decode a string (URLs) in Golang.
Golang provides built-in support for base64 encoding/decoding in the package encoding/base64.
Golang Encode and Decode Example using base64.URLEncoding
Here is an example of encoding and then decoding the URL using base64 encoding with URLEncoding.
package main
import (
    "encoding/base64"
    "fmt"
)
func main() {
    // String to encode
    str := "https://www.sourcecodeexamples.net/p/golang-source-code-examples.html"
    // It requires a byte slice so we cast the string to []byte
    encodedStr := base64.URLEncoding.EncodeToString([]byte(str))
    fmt.Println("Encoded:", encodedStr)
    // Decoding may return an error, in case the input is not well formed
    decodedStr, err := base64.URLEncoding.DecodeString(encodedStr )
    if err != nil {
        panic("malformed input")
    }
	
    fmt.Println("Decoded:", string(decodedStr))
}
Output:
Encoded: aHR0cHM6Ly93d3cuc291cmNlY29kZWV4YW1wbGVzLm5ldC9wL2dvbGFuZy1zb3VyY2UtY29kZS1leGFtcGxlcy5odG1s Decoded: https://www.sourcecodeexamples.net/p/golang-source-code-examples.html
Comments
Post a Comment