Freitag, 27. November 2009

base64 in golang


package main

import (
"encoding/base64";
"bytes";
"fmt";
)

func main() {
// create the buffer
bb := &bytes.Buffer{};
bbURL := &bytes.Buffer{};

// create two base64 encoder (standard and for url)
encoder := base64.NewEncoder(base64.StdEncoding, bb);
encoderURL := base64.NewEncoder(base64.URLEncoding, bbURL);

data := "hallo this is a test, a=23&var2=blabla+-?!%$/\\";
fmt.Println("data : ", data);

// to encode data, use Write([]bytes),
// therefore you must convert string to bytes
// with string.Bytes(d string)
encoder.Write([]byte(data));
encoder.Close();

encoderURL.Write([]byte(data));
encoderURL.Close();

// voila
fmt.Println("encoded Std: ", bb.String());
fmt.Println("encoded URL: ", bbURL.String());
}

1 Kommentar:

  1. thanks. idiomatic Go tell us to close resources using defer in order to avoid panics.

    AntwortenLöschen