mirror of
https://github.com/taigrr/wasm-experiments
synced 2025-01-18 04:03:21 -08:00
Add experimental Fetch API package
This commit is contained in:
parent
60bc902fb2
commit
5c7c23d888
7
fetch/Makefile
Normal file
7
fetch/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
build: clean compile
|
||||
|
||||
clean:
|
||||
rm -f ../html/test.wasm
|
||||
|
||||
compile:
|
||||
GOOS=js GOARCH=wasm GOROOT=$(GOPATH)/src/github.com/neelance/go/ $(GOPATH)/src/github.com/neelance/go/bin/go build -o ../html/test.wasm main.go
|
66
fetch/fetch/fetch.go
Normal file
66
fetch/fetch/fetch.go
Normal file
@ -0,0 +1,66 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime/js"
|
||||
)
|
||||
|
||||
type Method int
|
||||
|
||||
func (m Method) String() string {
|
||||
switch m {
|
||||
case GET:
|
||||
return "GET"
|
||||
case POST:
|
||||
return "POST"
|
||||
case PUT:
|
||||
return "PUT"
|
||||
case DELETE:
|
||||
return "DELETE"
|
||||
case PATCH:
|
||||
return "PATCH"
|
||||
}
|
||||
|
||||
panic("unsupported method")
|
||||
}
|
||||
|
||||
const (
|
||||
GET Method = iota
|
||||
POST
|
||||
PUT
|
||||
DELETE
|
||||
PATCH
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
Method Method
|
||||
URL *url.URL
|
||||
Headers http.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
URL url.URL
|
||||
Headers http.Header
|
||||
Body io.Reader
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func Fetch(req Request) (Response, error) {
|
||||
init := js.Global.Get("Object").New()
|
||||
init.Set("method", req.Method.String())
|
||||
init.Set("body", req.Body)
|
||||
|
||||
headers := js.Global.Get("Headers").New()
|
||||
for header, values := range req.Headers {
|
||||
for _, value := range values {
|
||||
headers.Call("append", header, value)
|
||||
}
|
||||
}
|
||||
init.Set("headers", headers)
|
||||
|
||||
promise := js.Global.Call("fetch", req.URL.String(), init)
|
||||
return Response{}, nil
|
||||
}
|
24
fetch/main.go
Normal file
24
fetch/main.go
Normal file
@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/johanbrandhorst/wasm-experiments/fetch/fetch"
|
||||
)
|
||||
|
||||
func main() {
|
||||
headers := http.Header{}
|
||||
headers.Add("Content-Type", "application/json")
|
||||
req := fetch.Request{
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: "httpbin.org",
|
||||
Path: "anything",
|
||||
},
|
||||
Method: fetch.POST,
|
||||
Body: []byte(`{"key": "value"}`),
|
||||
Headers: headers,
|
||||
}
|
||||
fetch.Fetch(req)
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user