github.com/lovishpuri/go-40569/src@v0.0.0-20230519171745-f8623e7c56cf/os/rawconn_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 // Test use of raw connections. 6 // 7 //go:build !plan9 && !js && !wasip1 8 9 package os_test 10 11 import ( 12 "os" 13 "syscall" 14 "testing" 15 ) 16 17 func TestRawConnReadWrite(t *testing.T) { 18 t.Parallel() 19 20 r, w, err := os.Pipe() 21 if err != nil { 22 t.Fatal(err) 23 } 24 defer r.Close() 25 defer w.Close() 26 27 rconn, err := r.SyscallConn() 28 if err != nil { 29 t.Fatal(err) 30 } 31 wconn, err := w.SyscallConn() 32 if err != nil { 33 t.Fatal(err) 34 } 35 36 var operr error 37 err = wconn.Write(func(s uintptr) bool { 38 _, operr = syscall.Write(syscallDescriptor(s), []byte{'b'}) 39 return operr != syscall.EAGAIN 40 }) 41 if err != nil { 42 t.Fatal(err) 43 } 44 if operr != nil { 45 t.Fatal(err) 46 } 47 48 var n int 49 buf := make([]byte, 1) 50 err = rconn.Read(func(s uintptr) bool { 51 n, operr = syscall.Read(syscallDescriptor(s), buf) 52 return operr != syscall.EAGAIN 53 }) 54 if err != nil { 55 t.Fatal(err) 56 } 57 if operr != nil { 58 t.Fatal(operr) 59 } 60 if n != 1 { 61 t.Errorf("read %d bytes, expected 1", n) 62 } 63 if buf[0] != 'b' { 64 t.Errorf("read %q, expected %q", buf, "b") 65 } 66 }