github.com/fisco-bcos/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/internal/obscuretestdata/obscuretestdata.go (about)

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package obscuretestdata contains functionality used by tests to more easily
     6  // work with testdata that must be obscured primarily due to
     7  // golang.org/issue/34986.
     8  package obscuretestdata
     9  
    10  import (
    11  	"encoding/base64"
    12  	"io"
    13  	"io/ioutil"
    14  	"os"
    15  )
    16  
    17  // DecodeToTempFile decodes the named file to a temporary location.
    18  // If successful, it returns the path of the decoded file.
    19  // The caller is responsible for ensuring that the temporary file is removed.
    20  func DecodeToTempFile(name string) (path string, err error) {
    21  	f, err := os.Open(name)
    22  	if err != nil {
    23  		return "", err
    24  	}
    25  	defer f.Close()
    26  
    27  	tmp, err := ioutil.TempFile("", "obscuretestdata-decoded-")
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  	if _, err := io.Copy(tmp, base64.NewDecoder(base64.StdEncoding, f)); err != nil {
    32  		tmp.Close()
    33  		os.Remove(tmp.Name())
    34  		return "", err
    35  	}
    36  	if err := tmp.Close(); err != nil {
    37  		os.Remove(tmp.Name())
    38  		return "", err
    39  	}
    40  	return tmp.Name(), nil
    41  }
    42  
    43  // ReadFile reads the named file and returns its decoded contents.
    44  func ReadFile(name string) ([]byte, error) {
    45  	f, err := os.Open(name)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	defer f.Close()
    50  	return ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
    51  }