本文整理汇总了Golang中io/ioutil.ReadFile函数的典型用法代码示例。如果您正苦于以下问题:Golang ReadFile函数的具体用法?Golang ReadFile怎么用?Golang ReadFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ReadFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestNewCRLFromFileWithoutRevocations
func TestNewCRLFromFileWithoutRevocations(t *testing.T) {
tryTwoKeyBytes, err := ioutil.ReadFile(tryTwoKey)
if err != nil {
t.Fatal(err)
}
tryTwoCertBytes, err := ioutil.ReadFile(tryTwoCert)
if err != nil {
t.Fatal(err)
}
crl, err := NewCRLFromFile([]byte("\n \n"), tryTwoCertBytes, tryTwoKeyBytes, "0")
if err != nil {
t.Fatal(err)
}
certList, err := x509.ParseDERCRL(crl)
if err != nil {
t.Fatal(err)
}
numCerts := len(certList.TBSCertList.RevokedCertificates)
expectedNum := 0
if expectedNum != numCerts {
t.Fatal("Wrong number of expired certificates")
}
}
示例2: main
func main() {
content, err := ioutil.ReadFile("studygolang.xml")
if err != nil {
log.Fatal(err)
}
var result Result
err = xml.Unmarshal(content, &result)
if err != nil {
log.Fatal(err)
}
log.Println(result)
log.Println(result.Persons[0].Name)
//input := "<?xml version=\"1.0\" encoding=\"GBK\"?><request><head><h_exch_code>800101</h_exch_code><h_bank_no>1111</h_bank_no><h_user_id>1038738897</h_user_id><h_branch_id>B00008211</h_branch_id><h_fact_date>20110321</h_fact_date><h_fact_time>16:28:30</h_fact_time><h_exch_date>20130929</h_exch_date><h_serial_no>123456</h_serial_no><h_rsp_code>hj123545</h_rsp_code><h_rsp_msg>ar</h_rsp_msg></head><body><record><user_pwd>54f9b3396fe28c208d525db21588965c</user_pwd></record></body></request>"
//inputReader := strings.NewReader(input)
content, err = ioutil.ReadFile("request.xml")
decoder := mahonia.NewDecoder("gb18030")
r := bufio.NewReader(decoder.NewReader(content))
if err != nil {
log.Fatal(err)
}
log.Println(content)
var request Request_800101
err = xml.Unmarshal(content, &request)
if err != nil {
log.Fatal(err)
}
log.Println(request)
}
示例3: GetLocalRootCA
// GetLocalRootCA validates if the contents of the file are a valid self-signed
// CA certificate, and returns the PEM-encoded Certificate if so
func GetLocalRootCA(baseDir string) (RootCA, error) {
paths := NewConfigPaths(baseDir)
// Check if we have a Certificate file
cert, err := ioutil.ReadFile(paths.RootCA.Cert)
if err != nil {
if os.IsNotExist(err) {
err = ErrNoLocalRootCA
}
return RootCA{}, err
}
key, err := ioutil.ReadFile(paths.RootCA.Key)
if err != nil {
if !os.IsNotExist(err) {
return RootCA{}, err
}
// There may not be a local key. It's okay to pass in a nil
// key. We'll get a root CA without a signer.
key = nil
}
rootCA, err := NewRootCA(cert, key, DefaultNodeCertExpiration)
if err == nil {
log.Debugf("successfully loaded the signer for the Root CA: %s", paths.RootCA.Cert)
}
return rootCA, err
}
示例4: main
func main() {
dat = make(map[string](map[string]string))
reportlog = make(map[string](map[string]string))
buf, _ := ioutil.ReadFile("static/data/data.json")
if len(buf) > 0 {
if err := json.Unmarshal(buf, &dat); err != nil {
panic(err)
}
}
buf, _ = ioutil.ReadFile("static/data/reportlog.json")
if len(buf) > 0 {
if err := json.Unmarshal(buf, &reportlog); err != nil {
panic(err)
}
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", index)
http.HandleFunc("/build", build) //设置访问的路由
http.HandleFunc("/setdat", setdat)
http.HandleFunc("/report", report)
http.HandleFunc("/upload", UploadServer)
err := http.ListenAndServe(dat["servermap"]["server"], nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例5: Regenerate
func (this *MixMatch) Regenerate() {
fmt.Printf("mixbench\n")
uuidData, err := ioutil.ReadFile("../uuid.go")
if err != nil {
panic(err)
}
if err := ioutil.WriteFile("./testdata/uuid.go", uuidData, 0666); err != nil {
panic(err)
}
data, err := ioutil.ReadFile("../thetest.proto")
if err != nil {
panic(err)
}
content := string(data)
for i, old := range this.Old {
content = strings.Replace(content, old, this.New[i], -1)
}
if err := ioutil.WriteFile("./testdata/thetest.proto", []byte(content), 0666); err != nil {
panic(err)
}
var regenerate = exec.Command("protoc", "--dgo_out=.", "-I="+config.ProtoPath, "./testdata/thetest.proto")
fmt.Printf("regenerating\n")
out, err := regenerate.CombinedOutput()
fmt.Printf("regenerate output: %v\n", string(out))
if err != nil {
panic(err)
}
}
示例6: main
func main() {
file := "file.txt"
r := gin.Default()
m := melody.New()
w, _ := fsnotify.NewWatcher()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleConnect(func(s *melody.Session) {
content, _ := ioutil.ReadFile(file)
s.Write(content)
})
go func() {
for {
ev := <-w.Events
if ev.Op == fsnotify.Write {
content, _ := ioutil.ReadFile(ev.Name)
m.Broadcast(content)
}
}
}()
w.Add(file)
r.Run(":5000")
}
示例7: loadECertAndEnrollmentPrivateKey
func loadECertAndEnrollmentPrivateKey(enrollmentID string, password string) ([]byte, *ecdsa.PrivateKey, error) {
cooked, err := ioutil.ReadFile("./test_resources/key_" + enrollmentID + ".dump")
if err != nil {
return nil, nil, err
}
block, _ := pem.Decode(cooked)
decryptedBlock, err := x509.DecryptPEMBlock(block, []byte(password))
if err != nil {
return nil, nil, err
}
enrollmentPrivateKey, err := x509.ParseECPrivateKey(decryptedBlock)
if err != nil {
return nil, nil, err
}
if err != nil {
return nil, nil, err
}
ecertRaw, err := ioutil.ReadFile("./test_resources/ecert_" + enrollmentID + ".dump")
if err != nil {
return nil, nil, err
}
return ecertRaw, enrollmentPrivateKey, nil
}
示例8: TestBuildGitbook
func TestBuildGitbook(t *testing.T) {
for _, example := range buildGitbookTests {
tempDir, _ := ioutil.TempDir("", "example")
defer os.RemoveAll(tempDir)
config := Config{
OpencontrolDir: example.inputDir,
Certification: example.certificationPath,
ExportPath: tempDir,
MarkdownPath: example.markdownPath,
}
config.BuildGitbook()
// Loop through the expected output to verify it matches the actual output
matches, _ := filepath.Glob(filepath.Join(example.expectedOutputDir, "*", "*"))
for _, expectedfilePath := range matches {
actualFilePath := strings.Replace(expectedfilePath, example.expectedOutputDir, tempDir, -1)
expectedData, _ := ioutil.ReadFile(expectedfilePath)
actualData, _ := ioutil.ReadFile(actualFilePath)
actualDataString := strings.Replace(string(actualData), "\\", "/", -1)
// Verify the expected text is the same as the actual text
if string(expectedData) != actualDataString {
t.Errorf("Expected (%s):\n`%s`\nActual:\n`%s`", expectedfilePath, string(expectedData), string(actualData))
}
}
}
}
示例9: compareFiles
func compareFiles(t *testing.T, expectedFN string, actualFN string) {
var expectedBytes []byte
var actualBytes []byte
var err error
expectedBytes, err = ioutil.ReadFile(expectedFN)
if err != nil {
t.Logf("Failed to open for compare: %s\n", err.Error())
t.Fail()
return
}
actualBytes, err = ioutil.ReadFile(actualFN)
if err != nil {
t.Logf("Failed to open for compare: %s\n", err.Error())
t.FailNow()
return
}
if len(expectedBytes) != len(actualBytes) {
t.Logf("%s and %s differ in size\n", expectedFN, actualFN)
t.Fail()
return
}
if 0 != bytes.Compare(actualBytes, expectedBytes) {
t.Logf("%s and %s differ\n", expectedFN, actualFN)
t.Fail()
return
}
}
示例10: TestUpdate
func TestUpdate(t *testing.T) {
file, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
if err := Build(file.Name(), "10.11.12.13", "testhostname", "testdomainname", nil); err != nil {
t.Fatal(err)
}
content, err := ioutil.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}
if expected := "10.11.12.13\ttesthostname.testdomainname testhostname\n"; !bytes.Contains(content, []byte(expected)) {
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
}
if err := Update(file.Name(), "1.1.1.1", "testhostname"); err != nil {
t.Fatal(err)
}
content, err = ioutil.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}
if expected := "1.1.1.1\ttesthostname.testdomainname testhostname\n"; !bytes.Contains(content, []byte(expected)) {
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
}
}
示例11: New
func New(quiet bool) *SysInfo {
sysInfo := &SysInfo{}
if cgroupMemoryMountpoint, err := cgroups.FindCgroupMountpoint("memory"); err != nil {
if !quiet {
log.Printf("WARNING: %s\n", err)
}
} else {
_, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.limit_in_bytes"))
_, err2 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.soft_limit_in_bytes"))
sysInfo.MemoryLimit = err1 == nil && err2 == nil
if !sysInfo.MemoryLimit && !quiet {
log.Printf("WARNING: Your kernel does not support cgroup memory limit.")
}
_, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes"))
sysInfo.SwapLimit = err == nil
if !sysInfo.SwapLimit && !quiet {
log.Printf("WARNING: Your kernel does not support cgroup swap limit.")
}
}
// Check if AppArmor seems to be enabled on this system.
if _, err := os.Stat("/sys/kernel/security/apparmor"); os.IsNotExist(err) {
sysInfo.AppArmor = false
} else {
sysInfo.AppArmor = true
}
return sysInfo
}
示例12: UpdateCapabilities
// FIXME: comment please!
func (runtime *Runtime) UpdateCapabilities(quiet bool) {
if cgroupMemoryMountpoint, err := utils.FindCgroupMountpoint("memory"); err != nil {
if !quiet {
log.Printf("WARNING: %s\n", err)
}
} else {
_, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.limit_in_bytes"))
_, err2 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.soft_limit_in_bytes"))
runtime.capabilities.MemoryLimit = err1 == nil && err2 == nil
if !runtime.capabilities.MemoryLimit && !quiet {
log.Printf("WARNING: Your kernel does not support cgroup memory limit.")
}
_, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes"))
runtime.capabilities.SwapLimit = err == nil
if !runtime.capabilities.SwapLimit && !quiet {
log.Printf("WARNING: Your kernel does not support cgroup swap limit.")
}
}
content, err3 := ioutil.ReadFile("/proc/sys/net/ipv4/ip_forward")
runtime.capabilities.IPv4ForwardingDisabled = err3 != nil || len(content) == 0 || content[0] != '1'
if runtime.capabilities.IPv4ForwardingDisabled && !quiet {
log.Printf("WARNING: IPv4 forwarding is disabled.")
}
// Check if AppArmor seems to be enabled on this system.
if _, err := os.Stat("/sys/kernel/security/apparmor"); os.IsNotExist(err) {
utils.Debugf("/sys/kernel/security/apparmor not found; assuming AppArmor is not enabled.")
runtime.capabilities.AppArmor = false
} else {
utils.Debugf("/sys/kernel/security/apparmor found; assuming AppArmor is enabled.")
runtime.capabilities.AppArmor = true
}
}
示例13: TestBundleWithECDSAKeyMarshalJSON
func TestBundleWithECDSAKeyMarshalJSON(t *testing.T) {
b := newCustomizedBundlerFromFile(t, testCFSSLRootBundle, testCFSSLIntBundle, "")
bundle, _ := b.BundleFromFile(leafECDSA256, leafKeyECDSA256, Optimal, "")
jsonBytes, err := json.Marshal(bundle)
if err != nil {
t.Fatal(err)
}
var obj map[string]interface{}
err = json.Unmarshal(jsonBytes, &obj)
if err != nil {
t.Fatal(err)
}
key := obj["key"].(string)
keyBytes, _ := ioutil.ReadFile(leafKeyECDSA256)
keyBytes = bytes.Trim(keyBytes, " \n")
if key != string(keyBytes) {
t.Fatal("key is not recovered.")
}
cert := obj["crt"].(string)
certBytes, _ := ioutil.ReadFile(leafECDSA256)
certBytes = bytes.Trim(certBytes, " \n")
if cert != string(certBytes) {
t.Fatal("cert is not recovered.")
}
keyType := obj["key_type"]
if keyType != "256-bit ECDSA" {
t.Fatal("Incorrect key type:", keyType)
}
}
示例14: NewBundler
// NewBundler creates a new Bundler from the files passed in; these
// files should contain a list of valid root certificates and a list
// of valid intermediate certificates, respectively.
func NewBundler(caBundleFile, intBundleFile string) (*Bundler, error) {
log.Debug("Loading CA bundle: ", caBundleFile)
caBundlePEM, err := ioutil.ReadFile(caBundleFile)
if err != nil {
log.Errorf("root bundle failed to load: %v", err)
return nil, errors.Wrap(errors.RootError, errors.ReadFailed, err)
}
log.Debug("Loading Intermediate bundle: ", intBundleFile)
intBundlePEM, err := ioutil.ReadFile(intBundleFile)
if err != nil {
log.Errorf("intermediate bundle failed to load: %v", err)
return nil, errors.Wrap(errors.IntermediatesError, errors.ReadFailed, err)
}
if _, err := os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {
log.Infof("intermediate stash directory %s doesn't exist, creating", IntermediateStash)
err = os.MkdirAll(IntermediateStash, 0755)
if err != nil {
log.Errorf("failed to create intermediate stash directory %s: %v",
IntermediateStash, err)
return nil, err
}
log.Infof("intermediate stash directory %s created", IntermediateStash)
}
return NewBundlerFromPEM(caBundlePEM, intBundlePEM)
}
示例15: NewSignerFromFile
// NewSignerFromFile reads the issuer cert, the responder cert and the responder key
// from PEM files, and takes an interval in seconds
func NewSignerFromFile(issuerFile, responderFile, keyFile string, interval time.Duration) (Signer, error) {
log.Debug("Loading issuer cert: ", issuerFile)
issuerBytes, err := ioutil.ReadFile(issuerFile)
if err != nil {
return nil, err
}
log.Debug("Loading responder cert: ", responderFile)
responderBytes, err := ioutil.ReadFile(responderFile)
if err != nil {
return nil, err
}
log.Debug("Loading responder key: ", keyFile)
keyBytes, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
}
issuerCert, err := helpers.ParseCertificatePEM(issuerBytes)
if err != nil {
return nil, err
}
responderCert, err := helpers.ParseCertificatePEM(responderBytes)
if err != nil {
return nil, err
}
key, err := helpers.ParsePrivateKeyPEM(keyBytes)
if err != nil {
log.Debug("Malformed private key %v", err)
return nil, err
}
return NewSigner(issuerCert, responderCert, key, interval)
}