LoginSignup
0
0

More than 1 year has passed since last update.

【Go】GitHub上の「特定の1ファイル」を取得する

Posted at

Go言語でAPIを使う練習のため、タイトルにある「GitHubのリポジトリにある特定の1ファイルの内容を取得する」プログラムを書いてみました。

取得するファイル(GitHubリポジトリ側)

今回はチュートリアル用のリポジトリから、以下のようなREADME.mdのコンテンツを取ってきてみたいと思います。

This is a script for API-tutorial

- feature-A
- fix-B
- feature-C

プログラム全文

package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    blobUrl := "https://api.github.com/repos/fugithora812/git-tutorial/contents/README.md"
    req, err := http.NewRequest("GET", blobUrl, nil)
    if err != nil {
        fmt.Println("failed: NewRequest")
    }
    req.Header.Set("Accept", "application/vnd.github.v3+json")

    client := new(http.Client)

    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("failed: DoReq")
    }
    defer resp.Body.Close()

    contents, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("failed: ReadAll")
    }

    var blob interface{}
    err = json.Unmarshal(contents, &blob)
    if err != nil {
        fmt.Println("failed: Unmarshal")
    }
    src := blob.(map[string]interface{})["content"]
    dec, err := base64.StdEncoding.DecodeString(src.(string))

    fmt.Println(string(dec))
}

実行結果

$ go run main.go
This is a script for API-tutorial

- feature-A
- fix-B
- feature-C

解説

解説はこちらをクリックして読めます。(私の個人ブログに遷移します)

0
0
0

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