diff --git a/kadai4/abemotion/main.go b/kadai4/abemotion/main.go new file mode 100644 index 0000000..4abb73b --- /dev/null +++ b/kadai4/abemotion/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "encoding/json" + "log" + "math/rand" + "net/http" + "time" +) + +type Fortune struct { + Result string `json:"result"` +} + +type Timer struct { + Now time.Time +} + +func main() { + t := &Timer{Now: time.Now()} + http.HandleFunc("/fortune", t.FortuneHandler) + + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func (t *Timer) FortuneHandler(w http.ResponseWriter, r *http.Request) { + fs := map[int]string{ + 0: "大吉", + 1: "中吉", + 2: "小吉", + 3: "吉", + 4: "末吉", + 5: "凶", + 6: "大凶", + } + rf := fs[rand.Intn(7)] + + if t.Now.Month().String() == "January" && arrayContains([]int{1, 2, 3}, t.Now.Day()) { + rf = "大吉" + } + + f := &Fortune{Result: rf} + enc := json.NewEncoder(w) + if err := enc.Encode(f); err != nil { + log.Fatal(err) + } +} + +func arrayContains(arr []int, str int) bool { + for _, v := range arr { + if v == str { + return true + } + } + return false +} diff --git a/kadai4/abemotion/main_test.go b/kadai4/abemotion/main_test.go new file mode 100644 index 0000000..f9a43c3 --- /dev/null +++ b/kadai4/abemotion/main_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestFortuneHandler(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/fortune", nil) + + tr := &Timer{Now: time.Date(2018, time.January, 2, 0, 0, 0, 0, time.UTC)} + tr.FortuneHandler(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 = "大吉" + if s := string(b); !strings.Contains(s, expected) { + t.Fatalf("unexpected response: %s", s) + } +}