Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions kadai4/abemotion/main.go
Original file line number Diff line number Diff line change
@@ -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
}
35 changes: 35 additions & 0 deletions kadai4/abemotion/main_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}