https://github.com/olebedev/go-duktape-fetch
Server side fetch polyfill for go-duktape
https://github.com/olebedev/go-duktape-fetch
Last synced: about 1 year ago
JSON representation
Server side fetch polyfill for go-duktape
- Host: GitHub
- URL: https://github.com/olebedev/go-duktape-fetch
- Owner: olebedev
- Created: 2015-06-12T12:10:55.000Z (about 11 years ago)
- Default Branch: v2
- Last Pushed: 2017-02-06T22:23:01.000Z (over 9 years ago)
- Last Synced: 2025-05-07T09:50:06.457Z (about 1 year ago)
- Language: Go
- Homepage:
- Size: 131 KB
- Stars: 12
- Watchers: 2
- Forks: 7
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-duktape-fetch [](https://app.wercker.com/project/bykey/fb4b5e19e7981f6aa9b0426deeaa1406)
Fetch polyfill for [go-duktape](https://github.com/olebedev/go-duktape).
### Usage
First of all install the package `go get gopkg.in/olebedev/go-duktape-fetch.v2`.
```go
package main
import (
"fmt"
"gopkg.in/olebedev/go-duktape.v2"
"gopkg.in/olebedev/go-duktape-fetch.v2"
)
func main() {
// create an ecmascript context
ctx := duktape.New()
// push fetch into the global scope
fetch.PushGlobal(ctx, nil)
ch := make(chan string)
ctx.PushGlobalGoFunction("cbk", func(c *duktape.Context) int {
ch <- c.SafeToString(-1)
return 0
})
// make a request
ctx.PevalString(`
fetch('http://ya.ru').then(function(resp) {
return resp.text();
}).then(function(body) {
// release channel
cbk(body.slice(0, 15));
});
`)
// print head line of the response body
fmt.Println(<-ch)
}
```
This program will prodice `` into stdout.
Also you can define fetch with some other good possibilities. In
particular you can specify local http instance with `http.Handler`
interface as a the second parameter. It will be used for all local
requests which url starts with `/`(single slash). See [tests](https://github.com/olebedev/go-duktape-fetch/blob/master/fetch_test.go)
for more detail.