github.com/gogf/gkafka@v1.0.1-0.20190702070843-033a14468069/third/golang.org/x/sys/unix/sendfile_test.go (about) 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. 4 5 // +build darwin,amd64 darwin,386 dragonfly freebsd linux solaris 6 7 package unix_test 8 9 import ( 10 "io/ioutil" 11 "net" 12 "os" 13 "path/filepath" 14 "testing" 15 16 "github.com/gogf/gkafka/third/golang.org/x/sys/unix" 17 ) 18 19 func TestSendfile(t *testing.T) { 20 // Set up source data file. 21 tempDir, err := ioutil.TempDir("", "TestSendfile") 22 if err != nil { 23 t.Fatal(err) 24 } 25 defer os.RemoveAll(tempDir) 26 name := filepath.Join(tempDir, "source") 27 const contents = "contents" 28 err = ioutil.WriteFile(name, []byte(contents), 0666) 29 if err != nil { 30 t.Fatal(err) 31 } 32 33 done := make(chan bool) 34 35 // Start server listening on a socket. 36 ln, err := net.Listen("tcp", "127.0.0.1:0") 37 if err != nil { 38 t.Skipf("listen failed: %s\n", err) 39 } 40 defer ln.Close() 41 go func() { 42 conn, err := ln.Accept() 43 if err != nil { 44 t.Fatal(err) 45 } 46 defer conn.Close() 47 b, err := ioutil.ReadAll(conn) 48 if string(b) != contents { 49 t.Errorf("contents not transmitted: got %s (len=%d), want %s", string(b), len(b), contents) 50 } 51 done <- true 52 }() 53 54 // Open source file. 55 src, err := os.Open(name) 56 if err != nil { 57 t.Fatal(err) 58 } 59 60 // Send source file to server. 61 conn, err := net.Dial("tcp", ln.Addr().String()) 62 if err != nil { 63 t.Fatal(err) 64 } 65 file, err := conn.(*net.TCPConn).File() 66 if err != nil { 67 t.Fatal(err) 68 } 69 var off int64 70 n, err := unix.Sendfile(int(file.Fd()), int(src.Fd()), &off, len(contents)) 71 if err != nil { 72 t.Errorf("Sendfile failed %s\n", err) 73 } 74 if n != len(contents) { 75 t.Errorf("written count wrong: want %d, got %d", len(contents), n) 76 } 77 // Note: off is updated on some systems and not others. Oh well. 78 // Linux: increments off by the amount sent. 79 // Darwin: leaves off unchanged. 80 // It would be nice to fix Darwin if we can. 81 if off != 0 && off != int64(len(contents)) { 82 t.Errorf("offset wrong: god %d, want %d or %d", off, 0, len(contents)) 83 } 84 // The cursor position should be unchanged. 85 pos, err := src.Seek(0, 1) 86 if err != nil { 87 t.Errorf("can't get cursor position %s\n", err) 88 } 89 if pos != 0 { 90 t.Errorf("cursor position wrong: got %d, want 0", pos) 91 } 92 93 file.Close() // Note: required to have the close below really send EOF to the server. 94 conn.Close() 95 96 // Wait for server to close. 97 <-done 98 }