Category Archives: Go

gke go

インストール

gcloud components update kubectl

手順

// イメージアップロード
gcloud docker -- push asia.gcr.io/rls-airpay/gke-test

gcloud container clusters create gke-test --zone asia-northeast1-a \
  --scopes cloud-platform \
  --num-nodes 2

gcloud container clusters get-credentials gke-test --zone asia-northeast1-a

kubectl create -f deployment.yaml

kubectl create -f service.yaml

kubectl describe service gke-test

参考

http://blog.kaneshin.co/entry/2016/12/15/133943

marshal 複合

パターン1

package main

import (
    "encoding/json"
    "log"
)

type User struct {
    Name string
}

type Comment struct {
    Text string
}

func (u User) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string]interface{}{
        "type":  "user",
        "value": u.Name,
    })
}

func (c Comment) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string]interface{}{
        "type":  "comment",
        "value": c.Text,
    })
}

func main() {
    u := User{Name: "yohei"}
    c := Comment{Text: "hello"}
    fields := []interface{}{u, c}
    b, _ := json.Marshal(fields)
    log.Print(string(b)) // [{"type":"user","value":"yohei"},{"type":"comment","value":"hello"}]
}

パターン2

package main

import (
    "encoding/json"
    "log"
)

type File struct {
    Key string
}

func (f File) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string]interface{}{
        "filekey":  f.Key,
    })
}

type Files []*File
func (fs Files) MarshalJSON() ([]byte, error) {
      return json.Marshal(struct{Value []*File}{Value: fs})

// 以下のようにmapにする必要はない
//    return json.Marshal(map[string][]*File{
//        "value":  fs,
//    })
}



func main() {
    f := File{Key: "test"}
    fs := Files{&f}
    b, _ := json.Marshal(fs)
    log.Print(string(b))
}

配列 固定長

array := make([]string, 5)
log.Print(array) // ブランクが5つ入った状態
if array[0] == ""{
    log.Print("blank!") // blank!と出力されることからも、blankが入っていることが確認できる
}
array[0] = "one"
log.Print(array) // 1つめの要素に"one"が入った状態

datastore

package controllers

import (
    "app-engine-test/app/models"
    "strconv"

    "github.com/gin-gonic/gin"
    "google.golang.org/appengine"
    "google.golang.org/appengine/datastore"
)

// Datastore ...
type Datastore struct{}

// Create ...
func (Datastore) Create(c *gin.Context) {
    ctx := appengine.NewContext(c.Request)
    var user models.User
    user.Name = "yyy"
    c.Bind(&user)
    key := datastore.NewIncompleteKey(ctx, "User", nil)
    _, err := datastore.Put(ctx, key, &user)
    if err != nil {
        c.JSON(500, err)
    } else {
        c.JSON(200, user)
    }
}

// GetsAll ...
func (Datastore) GetsAll(c *gin.Context) {
    ctx := appengine.NewContext(c.Request)
    q := datastore.NewQuery("User").Limit(10)
    users := make([]models.User, 0, 10)
    q.GetAll(ctx, &users)
    s := strconv.Itoa(len(users))
    c.String(200, s)
}

// Find ...
func (Datastore) Find(c *gin.Context) {
    ctx := appengine.NewContext(c.Request)
    users := make([]models.User, 0, 10)
    q := datastore.NewQuery("User").Filter("Name =", "yyy")
    q.GetAll(ctx, &users)
    s := strconv.Itoa(len(users))
    c.String(200, s)
}

配列分割

package main

import (
    "log"
)

// Chunks ...
func Chunks(array []int, n int) (output [][]int) {
    for i := 0; i < len(array); i++ {
        fromIndex := i
        toIndex := i + n
        if toIndex > len(array) {
            toIndex = len(array)
        }
        output = append(output, array[fromIndex:toIndex])
    }
    return
}

func main() {
    array := []int{1, 2, 3, 4, 5}
    output := Chunks(array, 2)
    log.Print(output)
}

代入文複数条件

代入分でも複数条件の処理ができる

func Test() (string, error) {
    return "aa", nil
}
func main() {
    if val, err := Test(); val == "aa" {
        log.Print("ok")
    } else if err != nil {
        log.Print("error!")
    }
}

gae go gin

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func init() {
    r := gin.Default()
    r.GET("/", handler)
    http.Handle("/", r)
}

func handler(c *gin.Context) {
    code := c.Query("code") // /?code=12345
    c.String(200, code)
}