7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Qiita APIをgoから叩いてみた

Last updated at Posted at 2020-10-13

はじめに

Go言語を勉強しなければという使命感にかられ、遊んでみることにしました。

golang + Qiita API

環境

・ go version go1.13 darwin/amd64

URIと機能

Path HTTPメソッド 機能
/qiita/api/v1/user-info GET 指定されたユーザの記事一覧を、作成日時の降順で返します。

使用パッケージ

・ gin
ginは、go製のWebフレームワークです。jsonレスポンス処理機能も持っている優れものです。

go get github.com/gin-gonic/gin

ファイル構成

❯ tree .
.
├── main.go
└── src
    └── controller
        └── controller.go

2 directories, 2 files

controller

mainから呼び出すタスク処理をまとめています。

controller.go
package controller

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"time"

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

type Item struct {
	Title     string    `json:"title"`
	CreatedAt time.Time `json:"created_at"`
}

// Qiita APIを叩く
func QiitaGET(c *gin.Context) {
	resp, err := http.Get("http://qiita.com/api/v2/users/{自身のアカウント名}/items?page=1&per_page=10")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	var data []Item

	if err := json.Unmarshal(body, &data); err != nil {
		log.Fatal(err)
	}

	c.JSON(http.StatusOK, gin.H{"item": data})
}

main

メイン処理を記述しました。

main.go
package main

import (
	"./src/controller"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	v1 := router.Group("/qiita/api/v1")
	{
		v1.GET("/user-info", controller.QiitaGET)
	}
	router.Run(":9000")
}

実行

❯ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /qiita/api/v1/user-info   --> _/Users/********/Desktop/Qiita_PoC_API/src/controller.QiitaGET (3 handlers)
[GIN-debug] Listening and serving HTTP on :9000

APIを叩く際には、postManを使用しました。
スクリーンショット 2020-10-12 23.22.24.png

参考

Qiita API

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?