Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Base64 encoding and decoding in Go

    package main
    
    import (
    	b64 "encoding/base64"
    	"fmt"
    )
    
    func main() {
    	str := "text123321!?$*&()'-=@~"
    
    	// Encode using the standard encoder
    	strEnc := b64.StdEncoding.EncodeToString([]byte(str))
    	fmt.Println(strEnc)
    
    	strDec, err := b64.StdEncoding.DecodeString(strEnc)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(string(strDec))
    	fmt.Println()
    
    	// Encode using a URL-compatible base64 format
    	strEnc = b64.URLEncoding.EncodeToString([]byte(str))
    	fmt.Println(strEnc)
    
    	strDec, err = b64.URLEncoding.DecodeString(strEnc)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(string(strDec))
    }
    
    // $ go run main.go
    // dGV4dDEyMzMyMSE/JComKCknLT1Afg==
    // text123321!?$*&()'-=@~
    
    // dGV4dDEyMzMyMSE_JComKCknLT1Afg==
    // text123321!?$*&()'-=@~

    Here is an example of base64 encoding and decoding. Go supports both standard and URL-compatible base64.