Skip to content

sv-tools/buffers-pool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

buffers-pool

Code Analysis Go Reference codecov GitHub tag (latest SemVer)

The small library with an implementation of Buffer Pool. The library was created to avoid repeating this code.

Here is a good article how to implement and properly use the Buffer Pools: https://www.captaincodeman.com/2017/06/02/golang-buffer-pool-gotcha

Check the tests file for some examples.

PS: The package is stable and the new releases are not expected.

Usage

package main

import (
	"fmt"
	"sync"
	"text/template"

	buffferspool "github.com/sv-tools/buffers-pool"
)

func render(tmpl string, data interface{}) (string, error) {
	tp, err := template.New("test").Parse(tmpl)
	if err != nil {
		return "", err
	}

	buf := buffferspool.Get()
	defer buffferspool.Put(buf)

	if err := tp.Execute(buf, data); err != nil {
		return "", err
	}

	// the usage of buf.String is safe 
	return buf.String(), nil
}

func main() {
    var tmpl string
    var data []interface{}
    // ... load template and data to variables ...

    var wg sync.WaitGroup
    res := make(chan string, len(data))
    for _, d := range data {
        wg.Add(1)
        go func(data interface{}) {
            defer wg.Done()
            val, err := render(tmpl, data)
            if err != nil {
                res <- err.Error()
                return
            }

            res <- val
        }(d)
    }

    wg.Wait()
    close(res)

    for val := range res {
    	fmt.Println(val)

    }
}

License

MIT licensed. See the bundled LICENSE file for more details.