LoginSignup
70
58

More than 5 years have passed since last update.

【個人メモ】Golang HTTP リクエストの内容をログに出す

Last updated at Posted at 2014-07-21

サンプルを元に。

Google Groupの投稿を元に、以下のスクリプトを書いた。
元にするスクリプトがあるため、著作権は元のスクリプトに準ずる。

package main

import (
    "bytes"
    "fmt"
    "log"
    "net/http"
    "text/template"
)

type LineOfLog struct {
    RemoteAddr  string
    ContentType string
    Path        string
    Query       string
    Method      string
    Body        string
}

var TemplateOfLog = `
Remote address:   {{.RemoteAddr}}
Content-Type:     {{.ContentType}}
HTTP method:      {{.Method}}

path:
{{.Path}}

query string:
{{.Query}}

body:             
{{.Body}}

`

func Log(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        bufbody := new(bytes.Buffer)
        bufbody.ReadFrom(r.Body)
        body := bufbody.String()

        line := LineOfLog{
            r.RemoteAddr,
            r.Header.Get("Content-Type"),
            r.URL.Path,
            r.URL.RawQuery,
            r.Method, body,
        }
        tmpl, err := template.New("line").Parse(TemplateOfLog)
        if err != nil {
            panic(err)
        }

        bufline := new(bytes.Buffer)
        err = tmpl.Execute(bufline, line)
        if err != nil {
            panic(err)
        }

        log.Printf(bufline.String())
        handler.ServeHTTP(w, r)
    })
}

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

    http.ListenAndServe(":8080", Log(http.DefaultServeMux))
}

ビルド・実行

main.goという形で上のスクリプトを保存して、

> go build main.go

でビルドして、

> ./main

で実行する

テスト

curlコマンドによるテスト

以下コマンドを打つ。
curlコマンドで、先ほど立ち上げたサーバに対しリクエストを送る。

> curl -X POST 'http://localhost:8080/test?hoge' -d '{"message": "Welcome to underground"}'

立ち上げたサーバ側の標準出力に、リクエストの内容が表示される。

Screen Shot 2014-07-21 at 9.20.49.png

faraday経由でテスト

faradayを使って、リクエストを送ってみる。

test.rb
require 'faraday'
require 'json'

conn = Faraday.new(url: 'http://localhost:8080/') do |faraday|
  faraday.request :url_encoded
  faraday.response :logger
  faraday.adapter Faraday.default_adapter

end

conn.post do |req|
  req.url '/'
  req.headers['Content-Type'] = 'application/json'
  req.body = { user: { id: 1, name: 'futoase' }, message: 'Welcome to underground...' }.to_json
end

以上のスクリプトを実行し、
サーバ側にリクエストを送る。

> ruby test.rb

結果。faradayのREADME.mdに書いてある通り。

Screen Shot 2014-07-21 at 9.35.45.png

終わり

目的がデバッグであり、リクエストの内容を観たいのであれば、
net catを使おう。

> nc -l 8080

で終わる。

> curl -X POST http://localhost:8080/ -H "Content-Type: application/json" -d '{"message": "Welcome to underround"}'

Screen Shot 2014-07-21 at 9.42.41.png

70
58
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
70
58