Skip to content

Commit

Permalink
generate cryptographically secure text in Sass
Browse files Browse the repository at this point in the history
  • Loading branch information
drewwells committed Jan 18, 2016
1 parent 614995f commit e93e2a4
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples/customfunc/README.md
Original file line number Diff line number Diff line change
@@ -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
}
```
53 changes: 53 additions & 0 deletions examples/customfunc/main.go
Original file line number Diff line number Diff line change
@@ -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'; }
}

0 comments on commit e93e2a4

Please sign in to comment.