Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kadai4 tk3fftk #70

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
14 changes: 14 additions & 0 deletions kadai4/tk3fftk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
## おみくじAPIを作ってみよう
### 制約
- [x] JSON形式でおみくじの結果を返す
- [x] 正月(1/1-1/3)だけ大吉にする
- テストにて動作確認しています
- [x] ハンドラのテストを書いてみる

### 使い方
```
$ go build -o lot
$ ./lot &
$ curl localhost:8080/lot
{"result":"大凶"}
```
13 changes: 13 additions & 0 deletions kadai4/tk3fftk/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import (
"net/http"

"github.com/gopherdojo/dojo3/kadai4/tk3fftk/omikuji"
)

func main() {
handler := omikuji.New(nil)
http.Handle("/lot", &handler)
http.ListenAndServe(":8080", nil)
}
88 changes: 88 additions & 0 deletions kadai4/tk3fftk/omikuji/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package omikuji

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)

const bigLuckey = "大吉"

type response struct {
Result string `json:"result"`
}

type Clock interface {
Now() time.Time
}

type ClockFunc func() time.Time

func (f ClockFunc) Now() time.Time {
return f()
}

type OmikujiHandler struct {
Clock Clock
Omikuji Omikuji
}

func New(clock Clock) OmikujiHandler {
o := NewOmikuji()
return OmikujiHandler{
Clock: clock,
Omikuji: o,
}
}

func (o *OmikujiHandler) createResponseJSON(result string) (string, error) {
res := &response{Result: result}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(res); err != nil {
return "", err
}
return buf.String(), nil
}

func (o *OmikujiHandler) handlerFunc(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")

var res string
var err error

if o.isNewYear() {
res, err = o.createResponseJSON(bigLuckey)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
lot := o.Omikuji.Do([]string{})
res, err = o.createResponseJSON(lot)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
fmt.Fprintf(w, res)
}

func (o *OmikujiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
o.handlerFunc(w, r)
}

func (o *OmikujiHandler) now() time.Time {
if o.Clock == nil {
return time.Now()
}
return o.Clock.Now()
}

func (o *OmikujiHandler) isNewYear() bool {
_, m, d := o.now().Date()
if m == 1 && d <= 3 {
return true
}
return false
}
95 changes: 95 additions & 0 deletions kadai4/tk3fftk/omikuji/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package omikuji

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestIsNewYear(t *testing.T) {
cases := map[string]struct {
month int
day int
expected bool
}{
"December31st": {
12,
31,
false,
},
"January1st": {
1,
1,
true,
},
"January2nd": {
1, 2, true,
},
"January3rd": {
1, 3, true,
},
"January4th": {
1, 4, false,
},
}

for k, v := range cases {
k := k
v := v

t.Run(k, func(t *testing.T) {
t.Helper()
handler := New(
ClockFunc(func() time.Time {
return time.Date(2018, time.Month(v.month), v.day, 6, 0, 0, 0, time.Local)
}),
)

if handler.isNewYear() != v.expected {
t.Errorf("expected=%v, actual=%v", v.expected, !v.expected)
}
})
}
}

func TestCreateResponseJSON(t *testing.T) {
handler := New(nil)
result := "test"
expected := "{\"result\":\"test\"}\n"
json, err := handler.createResponseJSON(result)
if err != nil {
t.Fatal("should not come here")
}
if strings.Compare(json, expected) != 0 {
t.Errorf("expected='%v', actual='%v'", expected, json)
}
}

func TestHandler(t *testing.T) {
handler := New(ClockFunc(func() time.Time {
return time.Date(2018, 1, 1, 6, 0, 0, 0, time.Local)
}))

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
handler.handlerFunc(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")
}
expected := "{\"result\":\"大吉\"}\n"

if s := string(b); s != expected {
t.Errorf("expected='%v', actual='%v'", expected, s)
}
}
35 changes: 35 additions & 0 deletions kadai4/tk3fftk/omikuji/omikuji.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package omikuji

import (
"math/rand"
"time"
)

var defaultLots = []string{
"大吉",
"吉",
"中吉",
"小吉",
"凶",
"大凶",
}

type Omikuji struct {
rand *rand.Rand
}

func NewOmikuji() Omikuji {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return Omikuji{
rand: r,
}
}

func (o *Omikuji) Do(lots []string) string {
l := len(lots)
if l != 0 {
return lots[rand.Intn(l)]
}

return defaultLots[rand.Intn(len(defaultLots))]
}
32 changes: 32 additions & 0 deletions kadai4/tk3fftk/omikuji/omikuji_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package omikuji

import (
"strings"
"testing"
)

func TestOmikuji_Do(t *testing.T) {
cases := map[string][]string{
"default": defaultLots,
"one": {"大吉"},
"two": {"大吉", "大凶"},
}

o := NewOmikuji()

for c := range cases {
c := c
t.Run(c, func(t *testing.T) {
t.Helper()

lots := cases[c]
lot := o.Do(lots)
for _, l := range lots {
if strings.Compare(lot, l) == 0 {
return
}
}
t.Errorf("%v should be included in %v", lot, lots)
})
}
}