diff --git a/fetch/fetch/fetch.go b/fetch/fetch/fetch.go index b1a9a66..b281757 100644 --- a/fetch/fetch/fetch.go +++ b/fetch/fetch/fetch.go @@ -2,7 +2,10 @@ package fetch +//go:generate bash -c "GOROOT=$GOPATH/src/github.com/neelance/go/ GOOS=js GOARCH=wasm stringer -type Method" + import ( + "errors" "fmt" "io" "net/http" @@ -13,28 +16,16 @@ import ( 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") -} - +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods const ( GET Method = iota + HEAD POST PUT DELETE + CONNECT + OPTIONS + TRACE PATCH ) @@ -42,20 +33,26 @@ type Request struct { Method Method URL *url.URL Headers http.Header - Body []byte + Body io.Reader } type Response struct { - URL url.URL + URL *url.URL Headers http.Header - Body io.Reader + Body io.ReadCloser StatusCode int } -func Fetch(req Request) (Response, error) { +func Fetch(req *Request) (*Response, error) { init := js.Global.Get("Object").New() init.Set("method", req.Method.String()) - init.Set("body", req.Body) + if req.Body != nil { + switch req.Method { + case GET, HEAD: + return nil, errors.New("cannot use body with GET or HEAD HTTP methods") + } + init.Set("body", req.Body) + } headers := js.Global.Get("Headers").New() for header, values := range req.Headers { @@ -71,5 +68,5 @@ func Fetch(req Request) (Response, error) { promise := js.Global.Call("fetch", req.URL.String(), init) promise.Call("then", cb) - return Response{}, nil + return &Response{}, nil } diff --git a/fetch/fetch/method_string.go b/fetch/fetch/method_string.go new file mode 100644 index 0000000..48b8180 --- /dev/null +++ b/fetch/fetch/method_string.go @@ -0,0 +1,16 @@ +// Code generated by "stringer -type Method"; DO NOT EDIT. + +package fetch + +import "strconv" + +const _Method_name = "GETHEADPOSTPUTDELETECONNECTOPTIONSTRACEPATCH" + +var _Method_index = [...]uint8{0, 3, 7, 11, 14, 20, 27, 34, 39, 44} + +func (i Method) String() string { + if i < 0 || i >= Method(len(_Method_index)-1) { + return "Method(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Method_name[_Method_index[i]:_Method_index[i+1]] +} diff --git a/fetch/main.go b/fetch/main.go index 9459111..d5ef6ea 100644 --- a/fetch/main.go +++ b/fetch/main.go @@ -3,6 +3,8 @@ package main import ( + "bytes" + "fmt" "net/http" "net/url" @@ -12,15 +14,15 @@ import ( func main() { headers := http.Header{} headers.Add("Content-Type", "application/json") - req := fetch.Request{ + req := &fetch.Request{ URL: &url.URL{ Scheme: "http", Host: "httpbin.org", Path: "anything", }, Method: fetch.POST, - Body: []byte(`{"key": "value"}`), + Body: bytes.NewBuffer([]byte(`{"key": "value"}`)), Headers: headers, } - fetch.Fetch(req) + fmt.Println(fetch.Fetch(req)) }