-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_handle_input_output_test.go
More file actions
59 lines (46 loc) · 1.18 KB
/
example_handle_input_output_test.go
File metadata and controls
59 lines (46 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package rip_test
import (
"bytes"
"context"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"github.com/dolanor/rip"
"github.com/dolanor/rip/encoding/json"
)
func ExampleHandle() {
toUpper := func(ctx context.Context, input string) (output string, err error) {
output = strings.ToUpper(input)
return output, nil
}
handler := rip.Handle(http.MethodPost, toUpper, rip.WithCodecs(json.Codec))
http.HandleFunc("/uppercase/", handler)
slog.Info("listening on :8888")
http.ListenAndServe(":8888", nil)
}
func toUpper(ctx context.Context, input string) (output string, err error) {
output = strings.ToUpper(input)
return output, nil
}
func ExampleHandle_withClient() {
handler := rip.Handle(http.MethodPost, toUpper, rip.WithCodecs(json.Codec))
http.HandleFunc("/uppercase/", handler)
ts := httptest.NewServer(http.DefaultServeMux)
defer ts.Close()
buf := bytes.NewBufferString(`"hello world"`)
res, err := http.Post(ts.URL+"/uppercase/", "application/json", buf)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
greeting, err := io.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", greeting)
// Output: "HELLO WORLD"
}