diff --git a/examples/customfunc/README.md b/examples/customfunc/README.md new file mode 100644 index 0000000..8fd8574 --- /dev/null +++ b/examples/customfunc/README.md @@ -0,0 +1,34 @@ +Cryptographically secure pseudorandom number generator in Sass. Well that is easy to do with this custom `crypto()` handler! + +Start by registering a Sass function with the name `crypt()`. Now when `crypto()` is found in Sass, the cryptotext Go function will be called. + +Input + +``` sass +div { text: crypto(); } + +``` + + +Output + +``` css +div { + text: 'c91db27d5e580ef4292e'; } +``` + +Sass function written in Go + +``` go +func cryptotext(ctx context.Context, usv libsass.SassValue) (*libsass.SassValue, error) { + + c := 10 + b := make([]byte, c) + _, err := rand.Read(b) + if err != nil { + return nil, err + } + res, err := libsass.Marshal(fmt.Sprintf("'%x'", b)) + return &res, err +} +``` diff --git a/examples/customfunc/main.go b/examples/customfunc/main.go new file mode 100644 index 0000000..4055ecf --- /dev/null +++ b/examples/customfunc/main.go @@ -0,0 +1,53 @@ +package main + +import ( + "bytes" + "crypto/rand" + "fmt" + "log" + "os" + + "golang.org/x/net/context" + + "github.com/wellington/go-libsass" +) + +// cryptotext is of type libsass.SassFunc. As libsass compiles the +// source Sass, it will look for `crypto()` then call this function. +func cryptotext(ctx context.Context, usv libsass.SassValue) (*libsass.SassValue, error) { + + c := 10 + b := make([]byte, c) + _, err := rand.Read(b) + if err != nil { + return nil, err + } + res, err := libsass.Marshal(fmt.Sprintf("'%x'", b)) + return &res, err +} + +func main() { + // Register a custom Sass func crypto + libsass.RegisterSassFunc("crypto()", cryptotext) + + // Input Sass source + input := `div { text: crypto(); }` + + buf := bytes.NewBufferString(input) + // Starts a compiler writing to Stdout and reading from + // a bytes buffer of the input source + comp, err := libsass.New(os.Stdout, buf) + if err != nil { + log.Fatal(err) + } + + // Run() kicks off the compiler and instructs libsass how + // to read our input, handling the output from libsass + if err := comp.Run(); err != nil { + log.Fatal(err) + } + + // Output: + // div { + // text: 'c91db27d5e580ef4292e'; } +}