Skip to content

Instantly share code, notes, and snippets.

@kentquirk
Created June 28, 2018 01:44
Show Gist options
  • Save kentquirk/50747c6415fad2218a8aa97892832810 to your computer and use it in GitHub Desktop.
Save kentquirk/50747c6415fad2218a8aa97892832810 to your computer and use it in GitHub Desktop.
Full hasher object with promises
package main
//go:generate gopherjs build --minify
import (
"crypto/sha256"
"errors"
"github.com/gopherjs/gopherjs/js"
"github.com/miratronix/jopher"
)
func main() {
js.Module.Get("exports").Set("newHasher", newHasher)
}
type Hasher struct {
*js.Object
S string `js:"s"`
Hash func(...interface{}) *js.Object `js:"hash"`
}
func newHasher(s string) *js.Object {
h := Hasher{Object: js.Global.Get("Object").New()}
h.S = s
h.Hash = jopher.Promisify(h.hash)
return h.Object
}
func (h *Hasher) hash() ([]byte, error) {
if h.S == "" {
return nil, errors.New("hash of an empty string")
}
r := sha256.New()
_, err := r.Write([]byte(h.S))
if err != nil {
return nil, err
}
return r.Sum(nil), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment