This is a creation in Article, where the information may have evolved or changed.
absrtact: This article mainly explains the file operation of the Go language. System Open\write, such as system call, often manipulate the file object is a file descriptor , and the C language library file operations need to rely on functions such as Fopen/fread, Their operands are file pointers . In the Go language, file operations are further encapsulated ...
File class in 1.os package
First, the file class is in the OS package, encapsulating the underlying document descriptor and related information, while encapsulating the read and write implementations.
typestruct { *file}typestruct { fd int string dirinfo *dirInfo nepipe int}func (f *File) Fd( )uintptr{ ifnil{ return ^(uintptr(0)) } returnuintptr(f.fd)}
Notice why you can use the F.FD syntax in the above, F is file, and file does not have a member?
func (f *File) Close() error{}func (f *File)Stat ()(fi FileInfo, err error){}
The file class also implements the following methods:
func (f *File) read(b []byteint, err error);func (f *File) write(b []byteint, err error) ;funcint64intint64, err error) ;
2.io. Readcloser
In the go language, with an ER suffix is often an interface, Readcloser, as the name implies, is an excuse to include the read and close methods. Let's take a look at the definitions and implementations of these two interfaces:
type Reader interface { Read(p []byte) (n int, err error)}type Closer interface { Close() error}
Note: The definition of reader in different packages is different, the following is the definition of reader in Bufio
3. Bufio Package
typestruct { // contains filtered or unexported fields}typestruct { buf []byte rd io.Reader r, w int err error lastByte int int}
Bufio is a buffered IO read-write package, let's look at an example:
PackageMainImport("FMT" "OS" "Bufio" "IO")funcMain () {f, err: = OS. Open ("C:\\aaa.txt")//Open File deferF.close ()//Open File error handling if Nil= = Err {buff: = Bufio. Newreader (f)//Read in cache for{line, err: = Buff. ReadString (' \ n ')//Read a line with ' \ n ' for Terminator ifErr! =Nil|| Io. EOF = = Err { Break} FMT. Print (line)//Can be processed on a single line} } }
Func Newreader (rd IO. Reader) *reader
Newreader returns a new Reader whose buffer has the default size.
4. Example
type Request struct { // The message body. ... Body io.ReadCloser ...}
So, if we want to implement the body of the request, we just need to implement the two interface in the IO package.