まずは固定文字列を返すだけのサーバーを書いてみます。
package main
import (
"fmt"
"net/http"
)
func rootHandler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Moke server")
}
func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}
ResponseWriterとRequestのポインタを受け取る関数を用意し、"/"でリクエストが来たらこれを実行する という形式で書きます。
go run ファイル名 で実行し、別ターミナルからcurlでリクエストを投げてみました。
$ curl -v -X GET 'http://localhost:8080'
< HTTP/1.1 200 OK
< Date: Tue, 01 Jul 2014 06:53:43 GMT
< Content-Length: 11
< Content-Type: text/plain; charset=utf-8
<
Moke server
ちゃんと動きました。Content-Typeはtext/plainになるようです。