Posted at

App Engine for Go からgithub APIを叩く

More than 3 years have passed since last update.


アクセストークンの生成

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
}
}