LoginSignup
19
16

More than 5 years have passed since last update.

App Engine for Go からgithub APIを叩く

Posted at

アクセストークンの生成

https://github.com/settings/tokens の手順に従いアクセストークンを生成する

Github APIを叩く!

App EngineからHttp Requestを投げる時はurlfetch apiを利用する
Authorizationにアクセストークンを入れるのを忘れずに!

Markdown API を叩いている雑な例

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"

    "google.golang.org/appengine"
    "google.golang.org/appengine/urlfetch"
)

type MarkdownPostParam struct {
    Text    string `json:"text"`
    Mode    string `json:"mode"`
    Context string `json:"context"`
}

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    param := MarkdownPostParam{
        Text:    "Hello Markdown,
        Mode:    "gfm",
        Context: "github/gollum",
    }
    paramBytes, err := json.Marshal(param)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    client := urlfetch.Client(ctx)
    req, err := http.NewRequest("POST", "https://api.github.com/markdown", bytes.NewReader(paramBytes))
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", fmt.Sprintf("token %s", "{your token}"))
    resp, err := client.Do(req)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

        body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}
19
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
16