1
0
mirror of https://github.com/taigrr/wasm-experiments synced 2025-01-18 04:03:21 -08:00

Couple small changes

Add extra HTTP verbs, Generate verb string representation,
disallow body for GET, HEAD, Use more pointers.
This commit is contained in:
Johan Brandhorst 2018-05-12 21:31:00 +01:00
parent 70424ed5a8
commit 8e3e7d54de
No known key found for this signature in database
GPG Key ID: 266C7D9B44EAA057
3 changed files with 41 additions and 26 deletions

View File

@ -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
}

View File

@ -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]]
}

View File

@ -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))
}