gce バッチ処理

gce

インスタンス作成

os: centos

起動スクリプト
startup-script

#! /bin/bash
sudo systemctl start nginx.service
go run /var/app/go/main.go

goインストール

// wgetインストール
yum install wget

// golangインストール
// 方法1
sudo yum install -y golang

// 方法2
cd /usr/local/src
sudo wget https://storage.googleapis.com/golang/go1.8.linux-amd64.tar.gz
sudo tar -C /usr/local/ -xzf go1.8.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin

// nginx install
sudo yum install -y nginx
sudo chkconfig nginx on
sudo systemctl start nginx.service

nginx

インストール

sudo yum install -y nginx
sudo chkconfig nginx on

設定

/etc/nginx/nginx.conf

server {
    listen       80;
    server_name  hostname;

    location / {
        fastcgi_pass  127.0.0.1:9000;
        include       fastcgi_params;
    }
}

起動

sudo systemctl start nginx.service

スクリプト

helloworld

package main
import (
    "fmt"
    "net"
    "net/http"
    "net/http/fcgi"
)
func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}
func main() {
    l, err := net.Listen("tcp", "127.0.0.1:9000")
    if err != nil {
        return
    }
    http.HandleFunc("/", handler)
    fcgi.Serve(l, nil)
}

slack通知

package main

import (
    "bytes"
    "log"
    "net/http"
)

func main() {
    const url = "https://hooks.slack.com/services/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"
    body := []byte(`{"text":"hello from gcp"}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
    if err != nil {
        log.Print(err)
    }
    req.Header.Set("Content-Type", "application/json; charset=UTF-8")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Print(err)
    }
    defer resp.Body.Close()
}

gce起動スクリプト

startup-script

#! /bin/bash
// nginx 起動
sudo systemctl start nginx.service

// golang 起動
go run /var/app/go/main.go