IBM Cloud Functions で Go を触ってみた

あけましておめでとうございます.
今年もよろしくお願いいたします.

さて、新年初めの書き初めは Go をやってみたいと思います.
IBM Cloud Functions で Go を動かしてみます.

今回試してみるのはこちらのサンプル.

Go のインストール

まずは Go のインストールします.

$ brew install go
$ go version
go version go1.11.4 darwin/amd64

Brew でインストールできるので Mac は簡単ですね.

 

Go のコーディング

サンプルのまんまです.

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": ("Happy New Year, " + name + " san!")}
    res, _ := json.Marshal(msg)
    fmt.Println(string(res))
}

 

IBM Cloud Functions へデプロイ

以下、デプロイまでの手順です.

  • Go のソースコードをビルド
  • Zip 圧縮
  • IBM Cloud Functions へデプロイ

まずはビルドです.

$ pwd
/Users/Santea/Desktop/wsk
$ ls
sample.go
$ GOOS=linux GOARCH=amd64 go build -o exec
$ ls
exec	sample.go

 
次に Zip 圧縮をします.

$ zip exec.zip exec
updating: exec (deflated 50%)
$ ls
exec	exec.zip	sample.go

 
最後にデプロイです.

$ bx wsk action create helloGo --native exec.zip
ok: created action helloGo

 
Public から呼びさせるように設定を修正します.

$ bx wsk action update helloGo --web true

 

実行

いざ実行です!

$ curl `bx wsk action get helloGo --url | tail -1`.json?name=Santea -i
HTTP/2 200 
date: Wed, 02 Jan 2019 09:19:10 GMT
content-type: application/json
content-length: 44
set-cookie: __cfduid=d4196e704350ab51af0396697699e099b1546420747; expires=Thu, 02-Jan-20 09:19:07 GMT; path=/; domain=.functions.cloud.ibm.com; HttpOnly
x-request-id: bf404e4de3d270705cccba12ddf36c8b
access-control-allow-origin: *
access-control-allow-methods: OPTIONS, GET, DELETE, POST, PUT, HEAD, PATCH
access-control-allow-headers: Authorization, Origin, X-Requested-With, Content-Type, Accept, User-Agent
x-openwhisk-activation-id: 6f6448af04fe45d9a448af04fed5d98c
ibm_cloud_functions: OpenWhisk
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
cf-ray: 492c2468ebb29505-NRT

{
  "msg": "Happy New Year!, Santea san !"
}

 

とりあえず書き初め成功(笑)
これから Go を勉強していきます.

 

以上です.