1 // Copyright 2018 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.
5 // +build darwin,amd64 darwin,386 dragonfly freebsd linux solaris
16 "golang.org/x/sys/unix"
19 func TestSendfile(t *testing.T) {
20 // Set up source data file.
21 tempDir, err := ioutil.TempDir("", "TestSendfile")
25 defer os.RemoveAll(tempDir)
26 name := filepath.Join(tempDir, "source")
27 const contents = "contents"
28 err = ioutil.WriteFile(name, []byte(contents), 0666)
33 done := make(chan bool)
35 // Start server listening on a socket.
36 ln, err := net.Listen("tcp", "127.0.0.1:0")
38 t.Skipf("listen failed: %s\n", err)
42 conn, err := ln.Accept()
44 t.Errorf("failed to accept: %v", err)
48 b, err := ioutil.ReadAll(conn)
50 t.Errorf("failed to read: %v", err)
53 if string(b) != contents {
54 t.Errorf("contents not transmitted: got %s (len=%d), want %s", string(b), len(b), contents)
60 src, err := os.Open(name)
65 // Send source file to server.
66 conn, err := net.Dial("tcp", ln.Addr().String())
70 file, err := conn.(*net.TCPConn).File()
75 n, err := unix.Sendfile(int(file.Fd()), int(src.Fd()), &off, len(contents))
77 t.Errorf("Sendfile failed %s\n", err)
79 if n != len(contents) {
80 t.Errorf("written count wrong: want %d, got %d", len(contents), n)
82 // Note: off is updated on some systems and not others. Oh well.
83 // Linux: increments off by the amount sent.
84 // Darwin: leaves off unchanged.
85 // It would be nice to fix Darwin if we can.
86 if off != 0 && off != int64(len(contents)) {
87 t.Errorf("offset wrong: god %d, want %d or %d", off, 0, len(contents))
89 // The cursor position should be unchanged.
90 pos, err := src.Seek(0, 1)
92 t.Errorf("can't get cursor position %s\n", err)
95 t.Errorf("cursor position wrong: got %d, want 0", pos)
98 file.Close() // Note: required to have the close below really send EOF to the server.
101 // Wait for server to close.