♻️ Simplify, no more util package

This commit is contained in:
Nicolas Lepage 2021-01-24 18:03:17 +01:00
parent a5c816d720
commit 37bf64f9dc
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
7 changed files with 19 additions and 29 deletions

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +0,0 @@
// Package whutil stands for WASM HTTP utilities.
//
// It contains internal utilities for github.com/nlepage/go-wasm-http-server.
package whutil

View File

@ -1,24 +1,27 @@
package whutil
package wasmhttp
import (
"syscall/js"
)
// Promise is JS Promise
// Promise is a JavaScript Promise
type Promise struct {
js.Value
}
type PromiseResolve func(...interface{}) js.Value
type PromiseReject func(...interface{}) js.Value
// NewPromise creates a new JS Promise
func NewPromise(cb func(resolve PromiseResolve, reject PromiseReject)) Promise {
// NewPromise creates a new JavaScript Promise
func NewPromise(cb func(resolve func(interface{}), reject func(interface{}))) Promise {
var cbFunc js.Func
cbFunc = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
defer cbFunc.Release()
cb(args[0].Invoke, args[1].Invoke)
cb(
func(value interface{}) {
args[0].Invoke(value)
},
func(value interface{}) {
args[1].Invoke(value)
},
)
return js.Undefined()
})
return Promise{js.Global().Get("Promise").New(cbFunc)}

View File

@ -1,4 +1,4 @@
package whutil
package wasmhttp
import (
"bytes"
@ -6,13 +6,8 @@ import (
"syscall/js"
)
// Request is a JS Request
type Request struct {
js.Value
}
// HTTPRequest builds and returns the equivalent http.Request
func (r Request) HTTPRequest() (*http.Request, error) {
// Request builds and returns the equivalent http.Request
func Request(r js.Value) (*http.Request, error) {
jsBody := js.Global().Get("Uint8Array").New(Promise{r.Call("arrayBuffer")}.Await())
body := make([]byte, jsBody.Get("length").Int())
js.CopyBytesToGo(body, jsBody)

View File

@ -1,4 +1,4 @@
package whutil
package wasmhttp
import (
"bytes"

View File

@ -5,8 +5,6 @@ import (
"net/http"
"strings"
"syscall/js"
"github.com/nlepage/go-wasm-http-server/internal/whutil"
)
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
@ -28,9 +26,7 @@ func Serve(handler http.Handler) func() {
}
var cb = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
var jsReq = whutil.Request{args[0]}
var resPromise = whutil.NewPromise(func(resolve whutil.PromiseResolve, reject whutil.PromiseReject) {
var resPromise = NewPromise(func(resolve func(interface{}), reject func(interface{})) {
go func() {
defer func() {
if r := recover(); r != nil {
@ -42,12 +38,12 @@ func Serve(handler http.Handler) func() {
}
}()
var req, err = jsReq.HTTPRequest()
var req, err = Request(args[0])
if err != nil {
panic(err)
}
var res = whutil.NewResponseWriter()
var res = NewResponseWriter()
h.ServeHTTP(res, req)