func restoreEnv(envs []string) {
	if envs != nil && len(envs) >= 0 {
		target := arrayToMap(envs)
		curr := arrayToMap(os.Environ())
		for nc, vc := range curr {
			vt, ok := target[nc]
			if !ok {
				os.Unsetenv(nc)
			} else if vc == vt {
				delete(target, nc)
			}
		}
		for nt, vt := range target {
			os.Setenv(nt, vt)
		}
	}
	envLock.Unlock()
}
restoreEnv restores the environment to be exactly as given in the array of strings
and unlocks the lock
package pkcs11
import (
	"os"
	"runtime"
	"strings"
	"sync"
	"github.com/pkg/errors"
)
var (
	envLock sync.Mutex
)
func setEnvVars(env map[string]string) ([]string, error) {
	envLock.Lock()
	if len(env) == 0 {
		return nil, nil
	}
	oldenv := os.Environ()
	for k, v := range env {
		err := os.Setenv(k, v)
		if err != nil {
			restoreEnv(oldenv)
			return nil, errors.Wrapf(err, "Could not set environment variable '%s' to '%s'", k, v)
		}
	}
	return oldenv, nil
}
func arrayToMap(elements []string) map[string]string {
	o := make(map[string]string)
	for _, element := range elements {
		p := strings.SplitN(element, "=", 2)
		if len(p) == 2 {
			o[p[0]] = p[1]
		}
	}
	return o
}