|
| 1 | +// This example is taken from https://github.com/dev-wasm/dev-wasm-go/blob/main/http/main.go |
| 2 | +// demonstrates how to use the wasihttp package to make HTTP requests using the `http.Client` interface. |
| 3 | +// |
| 4 | +// To run: `tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./examples/roundtrip` |
| 5 | +// Test: `wasmtime run -Shttp -Sinherit-network -Sinherit-env roundtrip.wasm` |
| 6 | +package main |
| 7 | + |
| 8 | +import ( |
| 9 | + "bytes" |
| 10 | + "fmt" |
| 11 | + "io" |
| 12 | + "net/http" |
| 13 | + |
| 14 | + wasihttp "go.bytecodealliance.org/x/wasihttp" |
| 15 | +) |
| 16 | + |
| 17 | +func printResponse(r *http.Response) error { |
| 18 | + fmt.Printf("Status: %d\n", r.StatusCode) |
| 19 | + for k, v := range r.Header { |
| 20 | + fmt.Printf("%s: %s\n", k, v[0]) |
| 21 | + } |
| 22 | + body, err := io.ReadAll(r.Body) |
| 23 | + if err != nil { |
| 24 | + return err |
| 25 | + } |
| 26 | + fmt.Printf("Body: \n%s\n", body) |
| 27 | + return nil |
| 28 | +} |
| 29 | + |
| 30 | +func main() { |
| 31 | + client := &http.Client{ |
| 32 | + Transport: &wasihttp.Transport{}, |
| 33 | + } |
| 34 | + req, err := http.NewRequest("GET", "https://postman-echo.com/get", nil) |
| 35 | + if err != nil { |
| 36 | + panic(err.Error()) |
| 37 | + } |
| 38 | + if req == nil { |
| 39 | + panic("Nil request!") |
| 40 | + } |
| 41 | + res, err := client.Do(req) |
| 42 | + if err != nil { |
| 43 | + panic(err.Error()) |
| 44 | + } |
| 45 | + defer res.Body.Close() |
| 46 | + |
| 47 | + err = printResponse(res) |
| 48 | + if err != nil { |
| 49 | + panic(err.Error()) |
| 50 | + } |
| 51 | + |
| 52 | + res, err = client.Post("https://postman-echo.com/post", "application/json", bytes.NewReader([]byte("{\"foo\": \"bar\"}"))) |
| 53 | + if err != nil { |
| 54 | + panic(err.Error()) |
| 55 | + } |
| 56 | + defer res.Body.Close() |
| 57 | + |
| 58 | + err = printResponse(res) |
| 59 | + if err != nil { |
| 60 | + panic(err.Error()) |
| 61 | + } |
| 62 | + |
| 63 | + req, err = http.NewRequest("PUT", "http://postman-echo.com/put", bytes.NewReader([]byte("{\"baz\": \"blah\"}"))) |
| 64 | + if err != nil { |
| 65 | + panic(err.Error()) |
| 66 | + } |
| 67 | + if req == nil { |
| 68 | + panic("Nil request!") |
| 69 | + } |
| 70 | + res, err = client.Do(req) |
| 71 | + if err != nil { |
| 72 | + panic(err.Error()) |
| 73 | + } |
| 74 | + defer res.Body.Close() |
| 75 | + |
| 76 | + err = printResponse(res) |
| 77 | + if err != nil { |
| 78 | + panic(err.Error()) |
| 79 | + } |
| 80 | +} |
0 commit comments