Skip to content

Instantly share code, notes, and snippets.

@ItalyPaleAle
Last active October 7, 2020 03:37
Show Gist options
  • Select an option

  • Save ItalyPaleAle/8e05e49216f77c44bbd6ca79809ea5ea to your computer and use it in GitHub Desktop.

Select an option

Save ItalyPaleAle/8e05e49216f77c44bbd6ca79809ea5ea to your computer and use it in GitHub Desktop.

Revisions

  1. ItalyPaleAle revised this gist Oct 7, 2020. No changes.
  2. ItalyPaleAle created this gist Oct 7, 2020.
    62 changes: 62 additions & 0 deletions http-request-wasm.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    // Copyright (C) 2020 Alessandro Segala (ItalyPaleAle)
    // License: MIT

    // MyGoFunc fetches an external resource by making a HTTP request from Go
    // The JavaScript method accepts one argument, which is the URL to request
    func MyGoFunc() js.Func {
    return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    // Get the URL as argument
    // args[0] is a js.Value, so we need to get a string out of it
    requestUrl := args[0].String()

    // Handler for the Promise
    // We need to return a Promise because HTTP requests are blocking in Go
    handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    resolve := args[0]
    reject := args[1]

    // Run this code asynchronously
    go func() {
    // Make the HTTP request
    res, err := http.DefaultClient.Get(requestUrl)
    if err != nil {
    // Handle errors: reject the Promise if we have an error
    errorConstructor := js.Global().Get("Error")
    errorObject := errorConstructor.New(err.Error())
    reject.Invoke(errorObject)
    return
    }
    defer res.Body.Close()

    // Read the response body
    data, err := ioutil.ReadAll(res.Body)
    if err != nil {
    // Handle errors here too
    errorConstructor := js.Global().Get("Error")
    errorObject := errorConstructor.New(err.Error())
    reject.Invoke(errorObject)
    return
    }

    // "data" is a byte slice, so we need to convert it to a JS Uint8Array object
    arrayConstructor := js.Global().Get("Uint8Array")
    dataJS := arrayConstructor.New(len(data))
    js.CopyBytesToJS(dataJS, data)

    // Create a Response object and pass the data
    responseConstructor := js.Global().Get("Response")
    response := responseConstructor.New(dataJS)

    // Resolve the Promise
    resolve.Invoke(response)
    }()

    // The handler of a Promise doesn't return any value
    return nil
    })

    // Create and return the Promise object
    promiseConstructor := js.Global().Get("Promise")
    return promiseConstructor.New(handler)
    })
    }