0% found this document useful (0 votes)
36 views4 pages

Go by Example:: Base64 Encoding

This document provides examples of reading files in Go. It demonstrates opening a file and reading bytes at specific locations or the entire contents. The bufio package is also shown to provide a buffered reader for more efficient reading of many small chunks. Errors are checked after each read operation and files should be closed when processing is complete.

Uploaded by

luluea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views4 pages

Go by Example:: Base64 Encoding

This document provides examples of reading files in Go. It demonstrates opening a file and reading bytes at specific locations or the entire contents. The bufio package is also shown to provide a buffered reader for more efficient reading of many small chunks. Errors are checked after each read operation and files should be closed when processing is complete.

Uploaded by

luluea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Go by Example: Base64 Encoding

Go provides built-in
support for base64
encoding/decoding.

package main

This syntax imports the


encoding/base64
package with the b64 name import b64 "encoding/base64"
instead of the default import "fmt"
base64. Itll save us some
space below.

func main() {

Heres the string well data := "abc123!?$*&()'-=@~"


encode/decode.

Go supports both standard


and URL-compatible
base64. Heres how to
encode using the standard sEnc := b64.StdEncoding.EncodeToString([]byte(data))
encoder. The encoder fmt.Println(sEnc)
requires a []byte so we
cast our string to that
type.

Decoding may return an


sDec, _ := b64.StdEncoding.DecodeString(sEnc)
error, which you can check fmt.Println(string(sDec))
if you dont already know fmt.Println()
the input to be well-formed.

uEnc := b64.URLEncoding.EncodeToString([]byte(data))
This encodes/decodes using fmt.Println(uEnc)
a URL-compatible base64 uDec, _ := b64.URLEncoding.DecodeString(uEnc)
format. fmt.Println(string(uDec))
}

The string encodes to slightly different values with the standard and URL base64 encoders (trailing
+ vs -) but they both decode to the original string as desired.

Go by Example: URL Parsing


URLs provide a uniform
way to locate resources.
Heres how to parse URLs
in Go.

package main

import "fmt"
import "net"
import "net/url"

func main() {

Well parse this example


URL, which includes a
scheme, authentication info, s := "postgres://user:[email protected]:5432/path?k=v#f"
host, port, path, query
params, and query
fragment.

u, err := url.Parse(s)
Parse the URL and ensure if err != nil {
there are no errors. panic(err)
}

Accessing the scheme is fmt.Println(u.Scheme)


straightforward.

User contains all


authentication info; call fmt.Println(u.User)
fmt.Println(u.User.Username())
Username and p, _ := u.User.Password()
Password on this for fmt.Println(p)
individual values.

The Host contains both the


hostname and the port, if fmt.Println(u.Host)
host, port, _ := net.SplitHostPort(u.Host)
present. Use fmt.Println(host)
SplitHostPort to fmt.Println(port)
extract them.

Here we extract the path


fmt.Println(u.Path)
and the fragment after the fmt.Println(u.Fragment)
#.

To get query params in a fmt.Println(u.RawQuery)


m, _ := url.ParseQuery(u.RawQuery)
string of k=v format, use fmt.Println(m)
RawQuery. You can also fmt.Println(m["k"][0])
parse query params into a }
map. The parsed query
param maps are from
strings to slices of strings,
so index into [0] if you
only want the first value.

Running our URL parsing program shows all the different pieces that we extracted.

Go by Example: Reading Files


Reading and writing files
are basic tasks needed for
many Go programs. First
well look at some
examples of reading files.

package main

import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)

Reading files requires func check(e error) {


checking most calls for if e != nil {
errors. This helper will panic(e)
streamline our error }
}
checks below.

func main() {

Perhaps the most basic file


dat, err := ioutil.ReadFile("/tmp/dat")
reading task is slurping a check(err)
files entire contents into fmt.Print(string(dat))
memory.

Youll often want more


control over how and what
parts of a file are read. For f, err := os.Open("/tmp/dat")
these tasks, start by check(err)
Opening a file to obtain
an os.File value.
Read some bytes from the
beginning of the file. b1 := make([]byte, 5)
n1, err := f.Read(b1)
Allow up to 5 to be read check(err)
but also note how many fmt.Printf("%d bytes: %s\n", n1, string(b1))
actually were read.

o2, err := f.Seek(6, 0)


You can also Seek to a check(err)
b2 := make([]byte, 2)
known location in the file n2, err := f.Read(b2)
and Read from there. check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2))

The io package provides


some functions that may o3, err := f.Seek(6, 0)
be helpful for file reading. check(err)
For example, reads like b3 := make([]byte, 2)
the ones above can be n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
more robustly
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
implemented with
ReadAtLeast.

There is no built-in
_, err = f.Seek(0, 0)
rewind, but Seek(0, check(err)
0) accomplishes this.

The bufio package


implements a buffered
reader that may be useful r4 := bufio.NewReader(f)
both for its efficiency with b4, err := r4.Peek(5)
many small reads and check(err)
fmt.Printf("5 bytes: %s\n", string(b4))
because of the additional
reading methods it
provides.

Close the file when youre


done (usually this would
be scheduled immediately f.Close()
after Opening with
defer).

You might also like