github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/net/sendfile_test.go (about) 1 // Copyright 2016 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 package net 6 7 import ( 8 "crypto/sha256" 9 "encoding/hex" 10 "fmt" 11 "io" 12 "os" 13 "testing" 14 ) 15 16 const ( 17 twain = "testdata/Mark.Twain-Tom.Sawyer.txt" 18 twainLen = 387851 19 twainSHA256 = "461eb7cb2d57d293fc680c836464c9125e4382be3596f7d415093ae9db8fcb0e" 20 ) 21 22 func TestSendfile(t *testing.T) { 23 ln, err := newLocalListener("tcp") 24 if err != nil { 25 t.Fatal(err) 26 } 27 defer ln.Close() 28 29 errc := make(chan error, 1) 30 go func(ln Listener) { 31 // Wait for a connection. 32 conn, err := ln.Accept() 33 if err != nil { 34 errc <- err 35 close(errc) 36 return 37 } 38 39 go func() { 40 defer close(errc) 41 defer conn.Close() 42 43 f, err := os.Open(twain) 44 if err != nil { 45 errc <- err 46 return 47 } 48 defer f.Close() 49 50 // Return file data using io.Copy, which should use 51 // sendFile if available. 52 sbytes, err := io.Copy(conn, f) 53 if err != nil { 54 errc <- err 55 return 56 } 57 58 if sbytes != twainLen { 59 errc <- fmt.Errorf("sent %d bytes; expected %d", sbytes, twainLen) 60 return 61 } 62 }() 63 }(ln) 64 65 // Connect to listener to retrieve file and verify digest matches 66 // expected. 67 c, err := Dial("tcp", ln.Addr().String()) 68 if err != nil { 69 t.Fatal(err) 70 } 71 defer c.Close() 72 73 h := sha256.New() 74 rbytes, err := io.Copy(h, c) 75 if err != nil { 76 t.Error(err) 77 } 78 79 if rbytes != twainLen { 80 t.Errorf("received %d bytes; expected %d", rbytes, twainLen) 81 } 82 83 if res := hex.EncodeToString(h.Sum(nil)); res != twainSHA256 { 84 t.Error("retrieved data hash did not match") 85 } 86 87 for err := range errc { 88 t.Error(err) 89 } 90 }