workspace/go/web下にserverディレクトリを作成する。

package main

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

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		dump, err := httputil.DumpRequest(req, true)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(dump))
		io.WriteString(w, "<html><body>hello world</body></html>")
	})
	err := http.ListenAndServe(":8889", nil)
	if err != nil {
		log.Fatal(err)
	}
}

http.HandleFuncは、今は"/"(トップページ)にクライアントからGet送信を受信した際にGetの中身をreqにいれて、サーバがクライアントに送信したい情報(レスポンス)を書き込む関数である。DumpRequest(req, true)は、クライアントから送信された情報を人が読み込める形に変換してくれる関数である。

http.ListenAndServeでポート番号8889を立ち上げてクライアントからアクセスできるようにする。

今回は、dumpにクライアントからの情報が入っているので、これをfmt.Println(string(dump))でstring型に変換して表示する。io.WriteString(w, HTMLで書かれた文字列)で、クライアントに送りたい内容、今回は"hello world"を変数wに書き込む。

MINGW64のコマンドラインに下記のコードを入力する。

$ cd ~/workspace/go/web/server/
$ go run server.go

ブラウザのアドレスバーやHTTPクライアントでlocalhost:8889にGET送信すると、hello worldが表示される。

hello


MINGW64にhttp.DumpRequestの内容を確認すると、

GET / HTTP/1.1
Host: localhost:8888
Accept-Encoding: gzip
User-Agent: Go-http-client/1.1

※Go言語で作成したクライアントからGET送信を行った場合の結果


上記の表示があった。