You can embed interfaces in a struct.

    package main

    import "fmt"

    type Mover interface {
            Move()
    }

    type Car struct {
            Mover
    }

But, what is embedded interface? Let’s add some more fields to Car and print it with %v.

    type Car struct {
            price int
            Mover
            speed int
    }

    func main() {
            var c Car
            fmt.Printf("%v\n", c)
    }       

It prints,

    $ go run main.go
    {0 <nil> 0}

As it printed out, Car has three fields. Embedded interface is just an anonymous interface fields.

Promoted methods

When interfaces are embedded, their methods are promoted automatically. That means methods of anonymous interface fields are seen as if they are methods of the embedding struct.

When you embed Mover interface in Car,

    type Car struct {
            Mover
    }

it works as if Cars has Move() methods defined as following.

    type Car struct {
            Mover
    }

    // promoted method
    func (c Car) Move() {
            c.Mover.Move()
    }

Note that calling Move() when the anonymous interface field is nil crashes the program.

    func main() {
            var m Mover = Car{} // Field 'Mover' is nil.
            m.Move() // Crashes. nil dereference.
    }

Override promoted methods

You can override all or a part of promoted methods if you want.

    type Car struct {
            Mover
    }

    type Wheel struct {
    }

    func (w Wheel) Move() {
            fmt.Println("wheel")
    }

    // Overrides promoted method
    func (c Car) Move() {
            fmt.Println("car")
    }

    func main() {
            var m Mover = Car{Wheel{}}
            m.Move() // Prints "car"
    }

Sort package has a good example of promoted method overriding.

Sort.Interface is as follows.

    type Interface interface {
            Len() int
            Less(i, j int) bool
            Swap(i, j int)
    }

    func Sort(data Interface) {
            ...
    }

sort.Reverse returns the reverse ordered data. It uses a struct which embeds sort.Interface and overrides only Less() method.

    func Reverse(data Interface) Interface {
            return &reverse{data}
    }

    type reverse struct {
            Interface // Interface embedding
    }

    // Overrides Less() only. No need to override promoted Len() and Swap().
    func (r reverse) Less(i, j int) bool {
            return r.Interface.Less(j, i)
    }

Make use of interface embedding for test

By embedding interfaces, promoted methods of interfaces satisfies the interfaces even though the anonymous field is nil.

    type Mover interface {
            Move()
    }

    type Car struct {
            Mover
    }

    func main() {
            // Car satisfies Mover interface because it has promoted Move() method.
            var m Mover = Car{} 
            m.Move() // Crashes. nil dereference.
    }

If you need to test only a part of the methods, you only need to implement the method needed. In following code, Car implements only Move() method explicitly. Car satisfies MoveStopper interface because it has promoted Stop() method.

    type MoveStopper interface {
            Move()
            Stop()
    }

    type Car struct {
            MoveStopper
    }

    func (c Car) Move() {
            fmt.Println("Move() tested")
    }

    func main() {
            var m MoveStopper = Car{}
            m.Move()
    }

Use x/text package to Read Japanese/Korean/Chinese encoded file.

import (
    "golang.org/x/text/encoding/japanese"
    "golang.org/x/text/transform"
)

func main() {
    var r io.Reader
    r = transform.NewReader(os.Stdin, japanese.ShiftJIS.NewDecoder())

Goncurrent is a Java library which provides the power of channel and select of Golang. Goncurrent works as you expect it to do.

Using channel:

Chan<Integer> ch1 = Chan.create(1)
ch1.send(0);
ch1.close();
Integer value;
value = ch1.receive(); // receives '0'
value = ch1.receive(); // receives null

Using select:

Chan<Integer> ch1 = Chan.create(0);
Chan<Integer> ch2 = Chan.create(0);
Chan<Integer> ch3 = Chan.create(0);
Chan<Integer> ch4 = Chan.create(0);

Select select = new Select();
while (true) {
    select.receive(ch1); // index=0
    select.receive(ch2); // index=1
    select.send(ch3, 10); // index=2
    select.send(ch4, 5); // index=3
    int index = select.select(); // wait until one of the channels is ready. 
    if (index == 0) {
        // data is read from ch1
        Integer value = (Integer)select.getData();
    }
}

When do you think calc1() and calc2() are called.

    for {
            fmt.Println("select start")
            select {
            case ch1 <- calc1():
                    fmt.Println("in case1")
            case ch2 <- calc2():
                    fmt.Println("in case2")
            }
            fmt.Println("select end")
    }

    func calc1() int {
            fmt.Println("in calc1")
            return 0
    }
    func calc2() int {
            fmt.Println("in calc2")
            return 0
    }

If you think calc1() is called 50% of the time when first case statement is chosen, it’s wrong.
calc1() and calc2() are called everytime upon entering select.

Considering the case where calc1() takes a long time to execute and there is another goroutine trying to send to ch1, calc1() need to be execured before “case” is chosen. Well designed behavior.

Look at the following code which uses empty struct.

    package main

    import "fmt"

    type someType struct{}

    func main() {

            val1 := new(someType)
            val2 := new(someType)

            fmt.Printf("%p\n", val1)
            fmt.Printf("%p\n", val2)

            fmt.Println(val1 == val2) // prints true
    }

Interestingly, the address of val1 and val2 is the same. If you want val1 and val2 to take different addresses, use something like int instread of struct{}

type someType int

path.Ext() returns a file name extension including a dot if exists.

import "path"

ext := path.Ext(infile)
outfile = infile[0:len(infile)-len(ext)] + ".newExt"

Add the following line at the top of the source code.

//usr/bin/env go run $0 $@ ; exit

Sample:

$ cat a.go
//usr/bin/env go run $0 $@; exit

package main

import "fmt"

func main() {
        fmt.Println("hello world")
}
$ chmod a+x a.go
$ ./a.go
hello world
$

see: http://unix.stackexchange.com/questions/162531/shebang-starting-with

Extract a HTTP POSTed zip file. req.Body can’t be passed directly to zip.NewReader() as it doesn’t implement ReadAt(). Wrap it with bytes.NewReader().

body, err := ioutil.ReadAll(req.Body)
if err != nil {
    // err
}   

r, err := zip.NewReader(bytes.NewReader(body), req.ContentLength)
if err != nil {
    // err
}   
for _, zf := range r.File {
    dst, err := os.Create(zf.Name)
    if err != nil {
        // err
    }
    defer dst.Close()
    src, err := zf.Open()
    if err != nil {
        // err
    }
    defer src.Close()

    io.Copy(dst, src)
}   

Note: this implementation doesn’t support subdirectory.

Use net/http/cgi.

package main

import (
    "net/http/cgi"
    "net/http"
    "fmt"
)

func errorResponse(code int, msg string) {
    fmt.Printf("Status:%d %s\r\n", code, msg)
    fmt.Printf("Content-Type: text/plain\r\n")
    fmt.Printf("\r\n")
    fmt.Printf("%s\r\n", msg)
}

func main() {

    var req *http.Request
    var err error
    req, err = cgi.Request()
    if err != nil {
        errorResponse(500, "cannot get cgi request" + err.Error())
        return
    }

    // Use req to handle request

    fmt.Printf("Content-Type: text/plain\r\n")
    fmt.Printf("\r\n")
    fmt.Printf("req=%v\r\n", req)
}

req.URL.Query() returns a map which implements Get() method.

func someHandler(w http.ResponseWriter, r *http.Request) {
    query := req.URL.Query()
    val1 := query.Get("key1")
    val2 := query.Get("key2")

Strings are URL-decoded automatically in URL.Query().

When method is GET, req.FormValue() can be also used to get query. However when method is POST, you need to use req.URL.Query().

Use net.InterfaceAddrs().

addrs, err := net.InterfaceAddrs()
if err != nil {
    panic(err)
}   
for i, addr := range addrs {
    fmt.Printf("%d %v\n", i, addr)
}   

If you want to know interface names too, use net.Interfaces() to get a list of interfaces first.

list, err := net.Interfaces()
if err != nil {
    panic(err)
}   

for i, iface := range list {
    fmt.Printf("%d name=%s %v\n", i, iface.Name, iface)
    addrs, err := iface.Addrs()
    if err != nil {
        panic(err)
    }
    for j, addr := range addrs {
        fmt.Printf(" %d %v\n", j, addr)
    }
}

Functions to add or remove pkcs#7 padding.

import (
    "bytes"
    "fmt"
)

// Appends padding.
func pkcs7Pad(data []byte, blocklen int) ([]byte, error) {
    if blocklen <= 0 {
        return nil, fmt.Errorf("invalid blocklen %d", blocklen)
    }
    padlen := 1
    for ((len(data) + padlen) % blocklen) != 0 {
        padlen = padlen + 1
    }

    pad := bytes.Repeat([]byte{byte(padlen)}, padlen)
    return append(data, pad...), nil
}

// Returns slice of the original data without padding.
func pkcs7Unpad(data []byte, blocklen int) ([]byte, error) {
    if blocklen <= 0 {
        return nil, fmt.Errorf("invalid blocklen %d", blocklen)
    }
    if len(data)%blocklen != 0 || len(data) == 0 {
        return nil, fmt.Errorf("invalid data len %d", len(data))
    }
    padlen := int(data[len(data)-1])
    if padlen > blocklen || padlen == 0 {
        return nil, fmt.Errorf("invalid padding")
    }
    // check padding
    pad := data[len(data)-padlen:]
    for i := 0; i < padlen; i++ {
        if pad[i] != byte(padlen) {
            return nil, fmt.Errorf("invalid padding")
        }
    }

    return data[:len(data)-padlen], nil
}

Sometimes, you want to specify a file to read with command line argument. Sometimes, you want to read from stdin. Following is a simple way to do it.

func openStdinOrFile() io.Reader {
    var err error
    r := os.Stdin
    if len(os.Args) > 1 {
        r, err = os.Open(os.Args[1])
        if err != nil {
            panic(err)
        }
    }
    return r
}

func main() {
    r := openStdinOrFile()
    readSomething(r)
}

In the following code, B is 0 because A doesn’t promote to uint16 or int automatically.

var A byte 
A = 1;

var B int 
B = int(A << 8)

You need to convert A to int explicitly.

var B int 
B = int(A) << 8

Linux supports three types of unix domain socket addresses. pathname, unnamed and abstract. abstract socket address is very convenient but there’s a pitfall of using it in Go.

If you want to use an abstract socket address, its name should starts with ’@’, not ’\0’.

net.UnixAddr{"@myname", "unix"} // address is {'\0','m','y','n','a','m','e' }

If address name starts with ’@’, Go converts ’@’ to ’\0’ and do not append ’\0’ at the end of the string.

If address name starts with ’\0’, the resulting address may not be what you want.

net.UnixAddr{"\x00myname", "unix"} // address is {'\0','m','y','n','a','m','e','\0'}