サンプルを元に。
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"}'
立ち上げたサーバ側の標準出力に、リクエストの内容が表示される。
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に書いてある通り。
終わり
目的がデバッグであり、リクエストの内容を観たいのであれば、
net catを使おう。
> nc -l 8080
で終わる。
> curl -X POST http://localhost:8080/ -H "Content-Type: application/json" -d '{"message": "Welcome to underround"}'