Skip to content

Commit c309a55

Browse files
committed
wip: added main (test failed)
1 parent 1b40d34 commit c309a55

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

kadai4/main.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"log"
6+
"net/http"
7+
)
8+
9+
func main() {
10+
http.HandleFunc("/", handler)
11+
http.ListenAndServe(":8080", nil)
12+
}
13+
14+
type Response struct {
15+
Msg string `json:"msg"`
16+
}
17+
18+
func handler(w http.ResponseWriter, r *http.Request) {
19+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
20+
21+
res := Response{Msg: "json response"}
22+
23+
if err := json.NewEncoder(w).Encode(res); err != nil {
24+
log.Println("Error:", err)
25+
}
26+
}
27+
28+
/*
29+
package main
30+
31+
import (
32+
"encoding/json"
33+
"log"
34+
"net/http"
35+
"time"
36+
37+
"github.com/isuzuki/omikuji/omikuji"
38+
)
39+
40+
func main() {
41+
http.HandleFunc("/", handler)
42+
http.ListenAndServe(":8080", nil)
43+
}
44+
45+
type Lottery struct {
46+
Msg string `json:"msg"`
47+
}
48+
49+
func handler(w http.ResponseWriter, r *http.Request) {
50+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
51+
52+
_, m, d := time.Now().Date()
53+
ret, ok := omikuji.Lottery(int(m), d)
54+
var res Lottery
55+
if ok {
56+
res = Lottery{Msg: ret}
57+
} else {
58+
res = Lottery{Msg: "エラーが発生しました。"}
59+
}
60+
61+
if err := json.NewEncoder(w).Encode(res); err != nil {
62+
log.Println("Error:", err)
63+
}
64+
}
65+
*/

kadai4/main_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import (
4+
"io/ioutil"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
)
9+
10+
func TestHandler(t *testing.T) {
11+
w := httptest.NewRecorder()
12+
r := httptest.NewRequest("GET", "/", nil)
13+
handler(w, r)
14+
rw := w.Result()
15+
16+
defer rw.Body.Close()
17+
18+
if rw.StatusCode != http.StatusOK {
19+
t.Fatalf("unexpected status code: %d", rw.StatusCode)
20+
}
21+
22+
b, err := ioutil.ReadAll(rw.Body)
23+
if err != nil {
24+
t.Fatal("unexpected error")
25+
}
26+
27+
const expected = `{"msg":"json response"}`
28+
if s := string(b); s != expected {
29+
t.Fatalf("unexpected response: %s", s)
30+
}
31+
}

0 commit comments

Comments
 (0)