当前位置: 首页>>代码示例>>Golang>>正文


Golang ioutil.ReadFile函数代码示例

本文整理汇总了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")
	}
}
开发者ID:jamesbjackson,项目名称:cfssl,代码行数:27,代码来源:crl_test.go

示例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)
}
开发者ID:gaohanejie,项目名称:test,代码行数:29,代码来源:testxml2.go

示例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
}
开发者ID:yugongpeng,项目名称:swarmkit,代码行数:32,代码来源:certificates.go

示例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)
	}
}
开发者ID:gwenlei,项目名称:linux,代码行数:26,代码来源:build.go

示例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)
	}
}
开发者ID:dropbox,项目名称:goprotoc,代码行数:28,代码来源:mixbench.go

示例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")
}
开发者ID:wuwenbao,项目名称:melody,代码行数:34,代码来源:main.go

示例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
}
开发者ID:yoshiharay,项目名称:fabric,代码行数:28,代码来源:tca_test.go

示例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))
			}
		}
	}
}
开发者ID:opencontrol,项目名称:compliance-masonry,代码行数:26,代码来源:gitbook_test.go

示例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
	}
}
开发者ID:jsummers,项目名称:gobmp,代码行数:31,代码来源:gobmp_test.go

示例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)
	}
}
开发者ID:winsx,项目名称:libnetwork,代码行数:33,代码来源:etchosts_test.go

示例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
}
开发者ID:beginnor,项目名称:docker,代码行数:29,代码来源:sysinfo.go

示例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
	}
}
开发者ID:jpellerin,项目名称:docker,代码行数:36,代码来源:runtime.go

示例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)
	}

}
开发者ID:bbandix,项目名称:cfssl,代码行数:35,代码来源:bundler_test.go

示例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)
}
开发者ID:hildjj,项目名称:boulder,代码行数:30,代码来源:bundler.go

示例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)
}
开发者ID:mclem,项目名称:cfssl,代码行数:37,代码来源:ocsp.go


注:本文中的io/ioutil.ReadFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。