基本
main.go
package main
import (
"fmt"
"log"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
// io.WriteString(w, "hello, world!\n") or
fmt.Fprint(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", hello)
log.Fatal(http.ListenAndServe(":8000", nil))
}
go run main.go
の後、コンソールから curl http://localhost:8000/hello
を実行すると、hello, world!
が返ってくる
ただ、POST で送信しても同様の結果になる (curl -X POST http://localhost:8000/hello
)
リクエストメソッドで出力変える
GET
と POST
でレスポンスを変えるには、r.Method
をチェックする必要がある
package main
import (
"fmt"
"log"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprint(w, "hello from GET\n")
} else {
fmt.Fprint(w, "hello from POST\n")
}
}
func main() {
http.HandleFunc("/hello", hello)
log.Fatal(http.ListenAndServe(":8000", nil))
}
これで GET
と POST
のリクエストに応じてレスポンスを変えられる
fmt.Fprint
or io.WriteString
どっちを使う?
上記のサンプルでは、fmt.Fprint
も io.WriteString
いずれでも問題なく動作するけど、結局何が違うの?
ということで、調べてみました。
関数 | シグネチャ |
---|---|
io.WriteString | func WriteString(w Writer, s string) (n int, err error) |
fmt.Fprint | func Fprint(w io.Writer, a ...interface{}) (n int, err error) |
結論から言うと、文字列 を出力する場合は io.WriteString
で、それ以外は、fmt.Fprint
で OK。
fmt.Fprint
の方が、複数の引数を渡せたり、型に縛られずに渡すことができる汎用性がある。