Author Archives: yoheimiyamoto

type 命名

package main

import "log"

// User ...
type User struct {
    Name string
}

// Users ...
type Users []*User

type myString string

func main() {
    u := User{Name: "yyy"}
    var us Users
    us = append(us, &u) // sliceのメソッドを使える
    log.Print(us[0].Name)

    s := myString("hello")
    log.Print(len(s)) // stringのメソッド使える
}

golang select2

API作成

api_handler.go

// Index ...
func Index(c *gin.Context) {
    ctx := appengine.NewContext(c.Request)
    httpclient := urlfetch.Client(ctx)
    client, err := kintone.NewClient(
        os.Getenv("KINTONE_DOMAIN"),
        os.Getenv("KINTONE_USER"),
        os.Getenv("KINTONE_PASSWORD"),
        "38",
        httpclient,
    )
    if err != nil {
        panic(err)
    }

    var us []*user
    query := c.DefaultQuery("q", "")
    if query != "" {
        query := fmt.Sprintf(`name like "%s"`, c.Query("q"))
        rs, err := client.GetRecords(query)
        if err != nil {
            panic(err)
        }
        for _, r := range rs {
            var u user
            u.ID = string(r.Fields["employee_number"].(kintone.SingleLineTextField))
            u.Text = string(r.Fields["name"].(kintone.SingleLineTextField))
            us = append(us, &u)
        }
    }
    if len(us) > 0 {
        c.JSON(200, us)
    } else {
        b := []byte(`[]`)
        c.JSON(200, string(b))
    }
}

レスポンス

[{"id":"1","text":"{名前1}"},{"id":"2","text":"{名前2}"},

ajax

$(function(){
  $('select').select2({
    placeholder: "名前か従業員番号を入力して、検索してください",
    ajax: {
        url: "http://localhost:8080/api/apps/40/records",
        delay: 250,
        cache: true,
        dataType: 'json',
        type: "GET",
        data: function(params) {
          return { q: params.term };
        },
        processResults: function (data, params) {
        return { results: $.map(data, function(obj) {
            return { id: obj.id, text: obj.text };
          })
        };
      }
    }
  })
});

html

<label>{{.FieldInfo.Label}}</label>
<select name={{.FieldInfo.Code}} class="form-control">
</select>

taskque module

app.yaml

application: test
module: dev  // module名セット
version: 2
runtime: go
api_version: go1.8

queue.yaml

queue:
- name: dev  // module名セット
  rate: 1/s
  mode: push
  target: dev  // module名セット
  max_concurrent_requests: 1
  retry_parameters:
    task_retry_limit: 3
    task_age_limit: 1d

queueセット

p := url.Values{
    "recordID": {w.Record.ID},
    "appID":    {w.App.ID},
}
task := taskqueue.NewPOSTTask(endpoint, p)
_, err := taskqueue.Add(ctx, task, "dev")  // module名セット
if err != nil {
    return err
}

構造体の比較

等しい場合

// User ...
type User struct {
    Value string
    Name  string
}

func main() {
    u1 := User{Value: "yyy", Name: "mmm"}
    u2 := User{Value: "yyy", Name: "mmm"}
    if u1 == u2 {
        log.Print("equal")
    }
}

等しくない場合

// User ...
type User struct {
    Value string
    Name  string
}

func main() {
    u1 := User{Value: "yyy", Name: "mmm"}
    u2 := User{Value: "yyy", Name: "mm"}
    if u1 == u2 {
        log.Print("equal")
    }
}

myInt

package main

import (
    "fmt"
    "strconv"

)

type myInt int

func main() {
    i := myInt(5)
    s := strconv.Itoa(int(i)) // myIntからintに変換が必要
    fmt.Println(s)
}

url.Values

package main

import (
    "fmt"
    "net/url"
)

func main() {
    u := url.Values{"name":{"hello"}}
    fmt.Println(u["name"][0]) // hello
}

参考

myStringの場合

package main

import (
    "fmt"
    "net/url" 

)

type myString string
type myInt int

func main() {
    s := myString("hello")
    u := url.Values{"name":{string(s)}} // mystringからstringに変換が必要
    fmt.Println(u["name"][0])
}

0埋め

package main

import (
    "fmt"
)

func main() {
    s := fmt.Sprintf("%04d", 200) // 4桁で0埋め
    fmt.Printf(s) // 0200
}

gin file post

fileData, header, err := c.Request.FormFile(fi.Code)
if err == nil && fileData != nil {
    fileName := header.Filename
    formData, formDataContentType, err := getFormData(fileData, fileName)
    if err != nil {
        return nil, err
    }
    fileKey, err := client.AddFile(formData.Bytes(), formDataContentType)
    if err != nil {
        return nil, err
    }
    fs = append(fs, &kintone.File{FileKey: fileKey})
}

func (c *Client) AddFile(body []byte, formDataContentType string) (fileKey string, err error) {
    req, err := http.NewRequest("POST", c.url(APIEndpointFile, ""), bytes.NewBuffer(body))
    if err != nil {
        return
    }
    req.Header.Set("Content-Type", formDataContentType)
    res, err := c.do(nil, req)
    if err != nil {
        return
    }
    body, err = ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        return
    }
    if res.StatusCode != 200 {
        err = fmt.Errorf(string(body))
        return
    }
    var t struct {
        FileKey string `json:"filekey"`
    }
    if err = json.Unmarshal(body, &t); err != nil {
        return
    }
    fileKey = t.FileKey
    return
}

func getFormData(fileData multipart.File, fileName string) (*bytes.Buffer, string, error) {
    formData := &bytes.Buffer{}
    writer := multipart.NewWriter(formData)
    h := make(textproto.MIMEHeader)
    h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileName))
    h.Set("Content-Type", "text/plain")
    fw, _ := writer.CreatePart(h)
    io.Copy(fw, fileData)
    formDataContentType := writer.FormDataContentType()
    writer.Close()
    return formData, formDataContentType, nil
}