Más contenido relacionado
La actualidad más candente (20)
Similar a Goでwebアプリを開発してみよう (20)
Goでwebアプリを開発してみよう
- 5. Hello, net/http パッケージ
■ まずは動かしてみよう
package main
import "fmt"
import "net/http"
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello, net/http!")
}
- 6. ハンドラ
■ ハンドラ
■ ハンドラの登録
func handler(w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello, net/http!")
}
http.HandleFunc("/", handler)
レスポンスを書き込むWriter
リクエスト
レスポンスの書き込み
/というパターンのパスで来たリクエストを
ハンドリングする関数を登録
- 16. ユーザ入力を受け付ける
■ リクエストからFormデータを取得する
func handler(w http.ResponseWriter,
r *http.Request) {
v := r.FormValue("myvalue")
fmt.Fprint(w, v)
}
<form action="/post" method="post">
<input type="text" name="myvalue">
<input type="submit" value="post">
</form>
Go
HTML
POSTで送られた
値を取得できる
- 23. テストの例
■ このコードをテストする
package main
import "fmt"
import "net/http"
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello, net/http!")
}
- 24. テストの例
func TestSample(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
handler(w, r)
rw := w.Result()
defer rw.Body.Close()
if rw.StatusCode != http.StatusOK {
t.Fatal("unexpected status code")
}
b, err := ioutil.ReadAll(rw.Body)
if err != nil {t.Fatal("unexpected error)}
const expected = "Hello, net/http!"
if s := string(b); s != expected {
t.Fatalf("unexpected response: %s", s)
}
}
テスト用のReponseWriterと
Requestを作る