With a sense of mission to study the Go language, I decided to play with it.
golang + Qiita API
・ Go version go1.13 darwin / amd64
Path | HTTP method | function |
---|---|---|
/qiita/api/v1/user-info | GET | Returns a list of articles for the specified user in descending order of creation date and time. |
** ・ Gin ** gin is a web framework made by go. It is an excellent one that also has a json response processing function.
go get github.com/gin-gonic/gin
❯ tree .
.
├── main.go
└── src
└── controller
└── controller.go
2 directories, 2 files
controller It summarizes the task processing called from 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"`
}
//Hit the Qiita API
func QiitaGET(c *gin.Context) {
resp, err := http.Get("http://qiita.com/api/v2/users/{Own account name}/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 Described the main process.
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
When hitting the API, I used postMan.
Recommended Posts