當前位置: 首頁>>代碼示例>>Golang>>正文


Golang io.Copy函數代碼示例

本文整理匯總了Golang中io.Copy函數的典型用法代碼示例。如果您正苦於以下問題:Golang Copy函數的具體用法?Golang Copy怎麽用?Golang Copy使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Copy函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Println(r.URL.Path)
		p := r.URL.Path[1:]
		if p == "" {
			p = "index.html"
		}
		fi, err := os.Open(p)
		if err == nil {
			defer fi.Close()
			io.Copy(w, fi)
			return
		}

		resp, err := http.Get("http://localhost:8080" + r.URL.Path)
		if err != nil {
			http.Error(w, err.Error(), 404)
			return
		}

		defer resp.Body.Close()
		io.Copy(w, resp.Body)
	})

	panic(http.ListenAndServe(":9117", nil))
}
開發者ID:whyrusleeping,項目名稱:cronus,代碼行數:26,代碼來源:proxy.go

示例2: serve

func (tp *TCPProxy) serve(in net.Conn) {
	var (
		err error
		out net.Conn
	)

	for i := 0; i < tp.numRemotes(); i++ {
		remote := tp.pick()
		if !remote.isActive() {
			continue
		}
		// TODO: add timeout
		out, err = net.Dial("tcp", remote.addr)
		if err == nil {
			break
		}
		remote.inactivate()
		plog.Warningf("deactivated endpoint [%s] due to %v for %v", remote.addr, err, tp.MonitorInterval)
	}

	if out == nil {
		in.Close()
		return
	}

	go func() {
		io.Copy(in, out)
		in.Close()
		out.Close()
	}()

	io.Copy(out, in)
	out.Close()
	in.Close()
}
開發者ID:ringtail,項目名稱:etcd,代碼行數:35,代碼來源:userspace.go

示例3: pipeStream

// pipeStream relays over a stream to a remote peer. It's like `cat`
func (rs *RelayService) pipeStream(src, dst peer.ID, s inet.Stream) error {
	s2, err := rs.openStreamToPeer(dst)
	if err != nil {
		return fmt.Errorf("failed to open stream to peer: %s -- %s", dst, err)
	}

	if err := WriteHeader(s2, src, dst); err != nil {
		return err
	}

	// connect the series of tubes.
	done := make(chan retio, 2)
	go func() {
		n, err := io.Copy(s2, s)
		done <- retio{n, err}
	}()
	go func() {
		n, err := io.Copy(s, s2)
		done <- retio{n, err}
	}()

	r1 := <-done
	r2 := <-done
	log.Infof("%s relayed %d/%d bytes between %s and %s", rs.host.ID(), r1.n, r2.n, src, dst)

	if r1.err != nil {
		return r1.err
	}
	return r2.err
}
開發者ID:avbalu,項目名稱:go-ipfs,代碼行數:31,代碼來源:relay.go

示例4: startPty

func (container *Container) startPty() error {
	ptyMaster, ptySlave, err := pty.Open()
	if err != nil {
		return err
	}
	container.ptyMaster = ptyMaster
	container.cmd.Stdout = ptySlave
	container.cmd.Stderr = ptySlave

	// Copy the PTYs to our broadcasters
	go func() {
		defer container.stdout.CloseWriters()
		utils.Debugf("[startPty] Begin of stdout pipe")
		io.Copy(container.stdout, ptyMaster)
		utils.Debugf("[startPty] End of stdout pipe")
	}()

	// stdin
	if container.Config.OpenStdin {
		container.cmd.Stdin = ptySlave
		container.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
		go func() {
			defer container.stdin.Close()
			utils.Debugf("[startPty] Begin of stdin pipe")
			io.Copy(ptyMaster, container.stdin)
			utils.Debugf("[startPty] End of stdin pipe")
		}()
	}
	if err := container.cmd.Start(); err != nil {
		return err
	}
	ptySlave.Close()
	return nil
}
開發者ID:hsolomon,項目名稱:docker,代碼行數:34,代碼來源:container.go

示例5: handleClient

func handleClient(p1, p2 net.Conn) {
	log.Println("stream opened")
	defer log.Println("stream closed")
	defer p1.Close()
	defer p2.Close()

	// start tunnel
	p1die := make(chan struct{})
	go func() {
		io.Copy(p1, p2)
		close(p1die)
	}()

	p2die := make(chan struct{})
	go func() {
		io.Copy(p2, p1)
		close(p2die)
	}()

	// wait for tunnel termination
	select {
	case <-p1die:
	case <-p2die:
	}
}
開發者ID:caidaoli,項目名稱:kcptun,代碼行數:25,代碼來源:main.go

示例6: fetchPubkey

func fetchPubkey() (*rsa.PublicKey, error) {
	resp, err := http.Get("https://s3o.ft.com/publickey")
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, errors.New("failed to read s3o public key")
	}
	defer func() {
		_, _ = io.Copy(ioutil.Discard, resp.Body)
		_ = resp.Body.Close()
	}()
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, resp.Body); err != nil {
		return nil, errors.New("failed to read s3o public key")
	}
	dec := make([]byte, 8192) // should be enough for a while.
	i, err := base64.StdEncoding.Decode(dec, buf.Bytes())
	if err != nil {
		return nil, errors.New("failed to base64 decode s3o public key")
	}

	pub, err := x509.ParsePKIXPublicKey(dec[0:i])
	if err != nil {
		return nil, errors.New("failed to parse s3o public key")
	}
	return pub.(*rsa.PublicKey), nil
}
開發者ID:railsagainstignorance,項目名稱:alignment,代碼行數:25,代碼來源:s3o.go

示例7: hashFile

// Generate a human readable sha1 hash of the given file path
func hashFile(path string) (hashes FileInfo, err error) {
	f, err := os.Open(path)
	if err != nil {
		return
	}
	defer f.Close()

	reader := bufio.NewReader(f)

	if GetConfig().Hashes.SHA1 {
		sha1Hash := sha1.New()
		_, err = io.Copy(sha1Hash, reader)
		if err == nil {
			hashes.Sha1 = hex.EncodeToString(sha1Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.SHA256 {
		sha256Hash := sha256.New()
		_, err = io.Copy(sha256Hash, reader)
		if err == nil {
			hashes.Sha256 = hex.EncodeToString(sha256Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.MD5 {
		md5Hash := md5.New()
		_, err = io.Copy(md5Hash, reader)
		if err == nil {
			hashes.Md5 = hex.EncodeToString(md5Hash.Sum(nil))
		}
	}
	return
}
開發者ID:ninetian,項目名稱:mirrorbits,代碼行數:33,代碼來源:utils.go

示例8: run

func run() (*bytes.Buffer, *bytes.Buffer) {
	out := new(bytes.Buffer)
	err := new(bytes.Buffer)

	re, e, _ := os.Pipe()
	ro, o, _ := os.Pipe()
	os.ForkExec(
		TEMPPATH,
		[]string{TEMPPATH},
		os.Environ(),
		"",
		[]*os.File{nil, o, e})

	e.Close()
	io.Copy(err, re)

	if err.Len() > 0 {
		return nil, err
	}

	o.Close()
	io.Copy(out, ro)

	return out, err
}
開發者ID:qrush,項目名稱:go-repl,代碼行數:25,代碼來源:main.go

示例9: compile

func compile(w *World) *bytes.Buffer {
	ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)

	err := new(bytes.Buffer)

	re, e, _ := os.Pipe()

	os.ForkExec(
		bin+"/"+arch+"g",
		[]string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"},
		os.Environ(),
		"",
		[]*os.File{nil, e, nil})

	e.Close()
	io.Copy(err, re)

	if err.Len() > 0 {
		return err
	}

	re, e, _ = os.Pipe()
	os.ForkExec(
		bin+"/"+arch+"l",
		[]string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"},
		os.Environ(),
		"",
		[]*os.File{nil, e, nil})

	e.Close()
	io.Copy(err, re)

	return err
}
開發者ID:qrush,項目名稱:go-repl,代碼行數:34,代碼來源:main.go

示例10: TestAsyncWriteTo

func TestAsyncWriteTo(t *testing.T) {
	buf := ioutil.NopCloser(bytes.NewBufferString("Testbuffer"))
	ar, err := newAsyncReader(buf, 4, 10000)
	if err != nil {
		t.Fatal("error when creating:", err)
	}

	var dst = &bytes.Buffer{}
	n, err := io.Copy(dst, ar)
	if err != io.EOF {
		t.Fatal("error when reading:", err)
	}
	if n != 10 {
		t.Fatal("unexpected length, expected 10, got ", n)
	}

	// Should still return EOF
	n, err = io.Copy(dst, ar)
	if err != io.EOF {
		t.Fatal("expected io.EOF, got", err)
	}
	if n != 0 {
		t.Fatal("unexpected length, expected 0, got ", n)
	}

	err = ar.Close()
	if err != nil {
		t.Fatal("error when closing:", err)
	}
}
開發者ID:kpabba,項目名稱:rclone,代碼行數:30,代碼來源:buffer_test.go

示例11: BenchmarkKiSS

func BenchmarkKiSS(b *testing.B) {
	go run_single_kiss_echo("127.0.0.1:1234")
	time.Sleep(time.Second)
	lololol, err := net.Dial("tcp", "127.0.0.1:1234")
	if err != nil {
		panic("wtf")
	}
	defer lololol.Close()
	xaxa, err := Obfs3fHandshake(lololol, false)
	if err != nil {
		panic(err.Error())
	}
	xaxa, err = TransportHandshake(dh_gen_key(2048), xaxa,
		func([]byte) bool { return true })
	xaxa, err = TransportHandshake(dh_gen_key(2048), xaxa,
		func([]byte) bool { return true })
	xaxa, err = TransportHandshake(dh_gen_key(2048), xaxa,
		func([]byte) bool { return true })
	xaxa, err = TransportHandshake(dh_gen_key(2048), xaxa,
		func([]byte) bool { return true })
	if err != nil {
		panic(err.Error())
	}
	defer xaxa.Close()
	fmt.Printf("xaxa!\n")
	listener, _ := net.Listen("tcp", "127.0.0.1:5555")
	client, _ := listener.Accept()
	defer client.Close()
	go io.Copy(client, xaxa)
	io.Copy(xaxa, client)
}
開發者ID:quantum1423-dustbin,項目名稱:kirisurf-legacy,代碼行數:31,代碼來源:transport_test.go

示例12: AttachPipes

func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error {
	command.Stdout = t.SlavePty
	command.Stderr = t.SlavePty

	go func() {
		if wb, ok := pipes.Stdout.(interface {
			CloseWriters() error
		}); ok {
			defer wb.CloseWriters()
		}

		io.Copy(pipes.Stdout, t.MasterPty)
	}()

	if pipes.Stdin != nil {
		command.Stdin = t.SlavePty
		command.SysProcAttr.Setctty = true

		go func() {
			io.Copy(t.MasterPty, pipes.Stdin)

			pipes.Stdin.Close()
		}()
	}
	return nil
}
開發者ID:TencentSA,項目名稱:docker-1.3,代碼行數:26,代碼來源:driver.go

示例13: RunCommandWithStdoutStderr

// RunCommandWithStdoutStderr execs a command and returns its output.
func RunCommandWithStdoutStderr(cmd *exec.Cmd) (bytes.Buffer, bytes.Buffer, error) {
	var stdout, stderr bytes.Buffer
	stderrPipe, err := cmd.StderrPipe()
	stdoutPipe, err := cmd.StdoutPipe()

	cmd.Env = os.Environ()
	if err != nil {
		fmt.Println("error at io pipes")
	}

	err = cmd.Start()
	if err != nil {
		fmt.Println("error at command start")
	}

	go func() {
		io.Copy(&stdout, stdoutPipe)
		fmt.Println(stdout.String())
	}()
	go func() {
		io.Copy(&stderr, stderrPipe)
		fmt.Println(stderr.String())
	}()
	time.Sleep(2000 * time.Millisecond)
	err = cmd.Wait()
	if err != nil {
		fmt.Println("error at command wait")
	}
	return stdout, stderr, err
}
開發者ID:tob1k,項目名稱:deisctl,代碼行數:31,代碼來源:utils.go

示例14: Attach

func (t *dockerTtyTerm) Attach(cmd *exec.Cmd) error {
	go io.Copy(t.pipes.Stdout, t.MasterPty)
	if t.pipes.Stdin != nil {
		go io.Copy(t.MasterPty, t.pipes.Stdin)
	}
	return nil
}
開發者ID:98pm,項目名稱:docker,代碼行數:7,代碼來源:term.go

示例15: runBin

func runBin(bin string, args []string) error {
	command = exec.Command(bin, args...)
	stdout, err := command.StdoutPipe()
	if err != nil {
		return err
	}
	stderr, err := command.StderrPipe()
	if err != nil {
		return err
	}

	err = command.Start()
	if err != nil {
		return err
	}

	startTime = time.Now()

	go io.Copy(writer, stdout)
	go io.Copy(writer, stderr)

	go func() {
		done <- command.Wait()
	}()

	return nil
}
開發者ID:ahall,項目名稱:app-reloader,代碼行數:27,代碼來源:main.go


注:本文中的io.Copy函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。