From 5c7c23d888e067fafd9ec466d180f911e96fb4cc Mon Sep 17 00:00:00 2001 From: Johan Brandhorst Date: Fri, 2 Mar 2018 21:26:42 +0000 Subject: [PATCH] Add experimental Fetch API package --- fetch/Makefile | 7 +++++ fetch/fetch/fetch.go | 66 ++++++++++++++++++++++++++++++++++++++++++++ fetch/main.go | 24 ++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 fetch/Makefile create mode 100644 fetch/fetch/fetch.go create mode 100644 fetch/main.go diff --git a/fetch/Makefile b/fetch/Makefile new file mode 100644 index 0000000..57b6bfd --- /dev/null +++ b/fetch/Makefile @@ -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 diff --git a/fetch/fetch/fetch.go b/fetch/fetch/fetch.go new file mode 100644 index 0000000..c9c9868 --- /dev/null +++ b/fetch/fetch/fetch.go @@ -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 +} diff --git a/fetch/main.go b/fetch/main.go new file mode 100644 index 0000000..fa89c9b --- /dev/null +++ b/fetch/main.go @@ -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) +}