Open In App

base64.DecodeString() Function in Golang With Examples

Go language provides inbuilt support for base64 encoding/decoding and has functions that could be used to perform operations on the given data using the base64 package. This package provides DecodeString() function which is used to decode a base64 string to its plaintext form. It supports decoding using both standard and URL compatible base64 standards.

Syntax:



func (enc *Encoding) DecodeString(s string) ([]byte, error)

The Encoding type used with the decoder has 4 variations:

Return Value: It returns the bytes represented by the given base64 string.



Below programs illustrate the DecodeString() function:

Example 1:




// Golang program to illustrate
// the base64.DecodeString() Function
package main
  
import (
    "encoding/base64"
    "fmt"
)
  
func main() {
  
    // taking a string
    givenString := "R2Vla3Nmb3JHZWVrcw=="
  
    // using the function
    decodedString, err := base64.StdEncoding.DecodeString(givenString)
    if err != nil {
        fmt.Println("Error Found:", err)
        return
    }
  
    fmt.Print("Decoded Bytes: ")
    fmt.Println(decodedString)
  
    fmt.Print("Decoded String: ")
    fmt.Println(string(decodedString))
}

Output:

Decoded Bytes: [71 101 101 107 115 102 111 114 71 101 101 107 115]
Decoded String: GeeksforGeeks

Example 2:




// Golang program to illustrate
// the base64.DecodeString() Function
package main
  
import (
    "encoding/base64"
    "fmt"
)
  
func main() {
  
    // taking a string
    givenString := "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv"
  
    // using the function
    decodedString, err := base64.URLEncoding.DecodeString(givenString)
    if err != nil {
        fmt.Println("Error Found:", err)
        return
    }
  
    fmt.Print("Decoded Bytes: ")
    fmt.Println(decodedString)
  
    fmt.Print("Decoded String: ")
    fmt.Println(string(decodedString))
}

Output:

Decoded Bytes: [104 116 116 112 115 58 47 47 119 119 119 46 103 101 101 107 115 102 111 114 103 101 101 107 115 46 111 114 103 47]
Decoded String: https://www.geeksforgeeks.org/


Article Tags :