-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcon.go
More file actions
43 lines (39 loc) · 1.18 KB
/
con.go
File metadata and controls
43 lines (39 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//go:build windows
package main
import (
"fmt"
"io"
"os"
"golang.org/x/sys/windows"
)
func openConsole() (io.Reader, error) {
handle, err := windows.GetStdHandle(windows.STD_INPUT_HANDLE)
if err != nil {
return nil, fmt.Errorf("GetStdHandle failed: %v", err)
}
fileType, err := windows.GetFileType(windows.Handle(handle))
if err != nil {
return nil, fmt.Errorf("GetFileType failed: %v", err)
}
var consoleFile *os.File
// FILE_TYPE_CHAR (0x0002) indicates a character device.
if fileType != windows.FILE_TYPE_CHAR {
consoleFile, err = os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return nil, fmt.Errorf("Failed to open CONIN$: %v", err)
}
return consoleFile, nil
}
// fileType is console
// Ensure we don't close the original handle.
var newHandle windows.Handle
err = windows.DuplicateHandle(windows.CurrentProcess(), handle, windows.CurrentProcess(), &newHandle, 0, false, windows.DUPLICATE_SAME_ACCESS)
if err != nil {
return nil, fmt.Errorf("DuplicateHandle failed: %v", err)
}
consoleFile = os.NewFile(uintptr(newHandle), "stdin")
if consoleFile == nil {
return nil, fmt.Errorf("Failed to create stdin from handle.")
}
return consoleFile, nil
}