From 25fb0ee319efd6b94ae8b193e0b4d40945f0cd98 Mon Sep 17 00:00:00 2001 From: Drew Wells Date: Mon, 18 Jan 2016 10:04:24 -0600 Subject: [PATCH] generate cryptographically secure text in Sass --- examples/customfunc/README.md | 34 ++++++++++++++++++++++ examples/customfunc/main.go | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 examples/customfunc/README.md create mode 100644 examples/customfunc/main.go diff --git a/examples/customfunc/README.md b/examples/customfunc/README.md new file mode 100644 index 0000000..dd988a2 --- /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 `crypto()`. 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'; } +}