Creating and invoking Go actions

Using OpenWhisk native actions, you can package any executable as an action. This works for Go as an example. As with Docker actions, the Go executable receives a single argument from the command line. It is a string serialization of the JSON object representing the arguments to the action. The program may log to stdout or stderr. By convention, the last line of output must be a stringified JSON object which represents the result of the action.

Here is an example Go action.

package main

import "encoding/json"
import "fmt"
import "os"

func main() {
    //program receives one argument: the JSON object as a string
    arg := os.Args[1]

    // unmarshal the string to a JSON object
    var obj map[string]interface{}
    json.Unmarshal([]byte(arg), &obj)

    // can optionally log to stdout (or stderr)
    fmt.Println("hello Go action")

    name, ok := obj["name"].(string)
    if !ok { name = "Stranger" }

    // last line of stdout is the result JSON object as a string
    msg := map[string]string{"msg": ("Hello, " + name + "!")}
    res, _ := json.Marshal(msg)
    fmt.Println(string(res))
}

Save the code above to a file sample.go and cross compile it for OpenWhisk. The executable must be called exec.

GOOS=linux GOARCH=amd64 go build -o exec
zip exec.zip exec
wsk action create helloGo --native exec.zip

The action may be run as any other action.

wsk action invoke helloGo -r -p name gopher
{
    "msg": "Hello, gopher!"
}

Find out more about parameters in the Working with parameters section.

Logs are retrieved in a similar way as well.

  wsk activation logs --last --strip
  my first Go action.