Created
June 28, 2018 01:44
-
-
Save kentquirk/50747c6415fad2218a8aa97892832810 to your computer and use it in GitHub Desktop.
Full hasher object with promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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