Skip to content
This repository was archived by the owner on Sep 27, 2020. It is now read-only.

Commit 08311ca

Browse files
committed
docs: more examples
1 parent 2d17c35 commit 08311ca

File tree

4 files changed

+96
-0
lines changed

4 files changed

+96
-0
lines changed

examples/01greeting/clock.go

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package greeting
2+
3+
import "time"
4+
5+
type Clock interface {
6+
Now() time.Time
7+
}
8+
9+
type ClockFunc func() time.Time
10+
11+
func (f ClockFunc) Now() time.Time {
12+
return f()
13+
}

examples/01greeting/greeting.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package greeting
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
)
7+
8+
func Greeting(hour int) string {
9+
if hour < 12 {
10+
return "Good morning"
11+
} else if 12 < hour && hour < 18 {
12+
return "Good afternoon"
13+
} else {
14+
return "Good evening"
15+
}
16+
}
17+
18+
type App struct {
19+
Clock Clock
20+
}
21+
22+
func (app *App) Greeting(w http.ResponseWriter, r *http.Request) {
23+
now := app.Clock.Now()
24+
w.Header().Set("Content-Type", "application/json")
25+
fmt.Fprintf(w, `{"message": %q, "time": %q}`, Greeting(now.Hour()), now)
26+
}
27+
28+
func (app *App) Mount(mux *http.ServeMux) {
29+
mux.HandleFunc("/greeting", app.Greeting)
30+
}

examples/01greeting/greeting_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package greeting
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
"time"
7+
8+
"github.com/podhmo/go-rfc3339"
9+
"github.com/podhmo/go-webtest"
10+
"github.com/podhmo/go-webtest/jsonequal"
11+
"github.com/podhmo/go-webtest/tripperware"
12+
"github.com/podhmo/noerror"
13+
)
14+
15+
func TestIt(t *testing.T) {
16+
app := &App{
17+
Clock: ClockFunc(func() time.Time {
18+
return rfc3339.MustParse("2000-01-01T00:00:00Z")
19+
}),
20+
}
21+
22+
var want interface{}
23+
client := webtest.NewClientFromHandler(http.HandlerFunc(app.Greeting))
24+
got, err := client.Get("/",
25+
webtest.WithTripperware(
26+
tripperware.ExpectCode(t, 200),
27+
tripperware.GetExpectedDataFromSnapshot(t, &want),
28+
),
29+
)
30+
noerror.Must(t, err)
31+
noerror.Should(t,
32+
jsonequal.ShouldBeSame(
33+
jsonequal.FromRawWithBytes(got.JSONData(), got.Body()),
34+
jsonequal.FromRaw(want),
35+
),
36+
)
37+
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"modifiedAt": "2020-08-09T00:59:03.193201+09:00",
3+
"data": {
4+
"request": {
5+
"method": "GET",
6+
"path": "/"
7+
},
8+
"response": {
9+
"data": {
10+
"message": "Good morning",
11+
"time": "2000-01-01 00:00:00 +0000 UTC"
12+
},
13+
"statusCode": 200
14+
}
15+
}
16+
}

0 commit comments

Comments
 (0)