tomatoaiu の Tech Blog

プログラミングやツールについてのまとめブログ

【Go】httpで通信したい

やりたいこと

Go言語で http の通信をしたい。まずは、クライアント側を Goで書いて、サーバー側は筆者が慣れているNode.jsのexpressを利用して書いてみる。その後に、文字列をhttpで返してみるサーバを今度はGoで書いてみる。
Goでhttp GETするためのライブラリについてはこちらに書いてあるので読んでおく。

Goクライアント + Expressサーバー

さっそく実装

イメージとしては、Node.jsのExpressを使ってhttp serverをhttp://localhost:3000で立てて、Go言語のhttpライブラリでhttp://localhost:3000に向けてHTTP Getしてくる感じ。HTTP GetでHello Worldできたらok。

環境

  • Node.js
  • Go
  • Visual Studio Code
  • zsh
  • iTerm2

導入

/go-playground/net
❯ touch http-get.go

/go-playground/net
❯ npm init -y

/go-playground/net
❯ touch server.js

/go-playground/net
❯ npm i express

ルートディレクトリ直下

  • http-get.go
  • server.js
  • package.json
  • package-lock.json
  • node_modules

http-get.go

package main


import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main()  {
    resp, err := http.Get("http://localhost:3000")
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

server.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
})

app.listen(3000);

実行

server側

/go-playground/net
❯ node server.js

client側

/go-playground/net
❯ go run http-get.go
Hello World

成果物

せっかく作ってみたのでgithubにて公開。 https://github.com/tomatoaiu/GoHttpGetSample

Goクライアント + Goサーバー

文字列を HTTP で返したい

クライアント側の処理をGoで書いてみて慣れたので、今度はGoで http server を立てる。

さっそく実装

今回はserverもclientもGo言語で書く。

環境

  • Go
  • Visual Studio Code
  • zsh
  • iTerm2

導入

/go-playground/server
❯ touch server.go

/go-playground/client
❯ touch client.go

ディレクトリ構造

  • /server/server.go
  • /client/client.go

server.go

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World")
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

client.js

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main()  {
    resp, err := http.Get("http://localhost:8080/hello")
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

実行

server側

/go-playground/server
❯ go run server.js

client側

/go-playground/client
❯ go run client.go
Hello, World

まとめ

Goクライアント + ExpressサーバーのHello worldとGoクライアント + Goサーバーの文字列を返すの二通りを実装してみた。とても簡単にGoでhttpメソッドを使った通信を実装することができた。
実装については、Fprintfhttp.ResponseWriterでclient側に文字列を返すことができるみたいだね。
ちなみに指定したuriがないとclient側では、404 page not foundっていう文字列が出る。

参考文献