2019年8月19日月曜日

開発環境

Head First Go (Jay McGavren(著)、O'Reilly Media)のChapter 15(responding to requests - Web Apps)、Exercise(434)の解答を求めてみる。

コード

package main

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

func write(writer http.ResponseWriter, message string, s string) {
 fmt.Println(s)
 _, err := writer.Write([]byte(message))
 if err != nil {
  log.Fatal(err)
 }
}

// handlerは無名関数で。
func main() {
 http.HandleFunc("/a",
  func(writer http.ResponseWriter, request *http.Request) {
   write(writer, "y", "/a")
  },
 )
 http.HandleFunc("/b",
  func(writer http.ResponseWriter, request *http.Request) {
   write(writer, "z", "/b")
  },
 )
 http.HandleFunc("/c",
  func(writer http.ResponseWriter, request *http.Request) {
   write(writer, "x", "/c")
  },
 )
 // x http://localhost:4567/c
 // y http://localhost:4567/a
 // z http://localhost:4567/b
 err := http.ListenAndServe("localhost:4567", nil)
 log.Fatal(err)
}

入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)

$ go run sample1.go
/c
/a
/b
/b
  C-c C-csignal: interrupt
$ 

0 コメント:

コメントを投稿