Go言語でスクレイピングとWebサーバーを開発する手順を書いていきます。
# 開発環境構築
$ brew install go
# プロジェクトのディレクトリ作成
$ mkdir scraping-server
$ cd scraping-server
$ go mod init scraping-server
# 外部パッケージのインストール
$ go get github.com/gin-gonic/gin
$ go get github.com/PuerkitoBio/goquery
インストールしている外部パッケージは以下のものです。
まず以下の内容で main.go を作成します。
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "test")
})
router.Run(":3000")
}
その後、以下コマンドを実行して http://localhost:3000 にブラウザでアクセスすると、”test” の文字が表示されます。
$ go run main.go
これで、Webサーバーの起動ができました。
main.go に以下の実装を追加します。
package main
import (
"net/http"
"log"
"github.com/gin-gonic/gin"
// パッケージの追加
"github.com/PuerkitoBio/goquery"
)
// スクレイピング用の関数を追加
func Scrape() []string {
res, err := http.Get("https://en.wikipedia.org/wiki/List_of_programming_languages")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
items := []string{}
doc.Find(".div-col li").Each(func(i int, s *goquery.Selection) {
items = append(items, s.Text())
})
return items
}
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
// 追加した関数を使用する
items := Scrape()
c.JSON(http.StatusOK, items)
})
router.Run(":3000")
}
追加実装の後、 $ go run main.go を再実行して http://localhost:3000 にアクセスすると、 Wikipediaのページから取得したプログラミング言語一覧の文字が表示されるようになります。