-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathroundtrip.go
80 lines (71 loc) · 1.73 KB
/
roundtrip.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// This example is taken from https://github.com/dev-wasm/dev-wasm-go/blob/main/http/main.go
// demonstrates how to use the wasihttp package to make HTTP requests using the `http.Client` interface.
//
// To run: `tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./examples/roundtrip`
// Test: `wasmtime run -Shttp -Sinherit-network -Sinherit-env roundtrip.wasm`
package main
import (
"bytes"
"fmt"
"io"
"net/http"
wasihttp "github.com/ydnar/wasi-http-go/wasihttp"
)
func printResponse(r *http.Response) error {
fmt.Printf("Status: %d\n", r.StatusCode)
for k, v := range r.Header {
fmt.Printf("%s: %s\n", k, v[0])
}
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
fmt.Printf("Body: \n%s\n", body)
return nil
}
func main() {
client := &http.Client{
Transport: &wasihttp.Transport{},
}
req, err := http.NewRequest("GET", "https://postman-echo.com/get", nil)
if err != nil {
panic(err.Error())
}
if req == nil {
panic("Nil request!")
}
res, err := client.Do(req)
if err != nil {
panic(err.Error())
}
defer res.Body.Close()
err = printResponse(res)
if err != nil {
panic(err.Error())
}
res, err = client.Post("https://postman-echo.com/post", "application/json", bytes.NewReader([]byte("{\"foo\": \"bar\"}")))
if err != nil {
panic(err.Error())
}
defer res.Body.Close()
err = printResponse(res)
if err != nil {
panic(err.Error())
}
req, err = http.NewRequest("PUT", "http://postman-echo.com/put", bytes.NewReader([]byte("{\"baz\": \"blah\"}")))
if err != nil {
panic(err.Error())
}
if req == nil {
panic("Nil request!")
}
res, err = client.Do(req)
if err != nil {
panic(err.Error())
}
defer res.Body.Close()
err = printResponse(res)
if err != nil {
panic(err.Error())
}
}