This is a creation in Article, where the information may have evolved or changed.
1. Function type conversions for Golang
A Go playground example, first defines a Func type alias A, and then defines a method. Define a function that has the same parameters as the return value (so that it can be explicitly converted). In main, this function is explicitly converted to type a so that it can invoke the method of a.
Package Mainimport "FMT" type A func (int, int) func (f A) Serve () {fmt. Println ("Serve2")}func serve (int,int) {fmt. Println ("serve1")}func Main () {A: = A (serve) a (+) A.serve ()}
2. Golang's HTTP packet processing process
Func HelloServer (w http. Responsewriter, req *http. Request) {io. WriteString (W, "Hello, world!\n")} Func Main () {http. Handlefunc ("/hello", HelloServer) Err: = http. Listenandserve (": 12345", nil) if err! = Nil {log. Fatal ("Listenandserve:", Err)}}
First Call Http.handlefunc
In order to do a few things:
1 called the Handlefunc of Defaultservermux.
2 called the handle of Defaultservermux.
3 Add the corresponding handler and routing rules to the map[string]muxentry in Defaultservemux
Next, call HTTP. Listenandserve (": 12345", nil)
In order to do a few things:
1 instantiating the server
2 calling the server's Listenandserve ()
3 Call net. Listen ("tcp", addr) Listening port
4 Start A For loop, accept requests in the loop body
5 instantiate a conn for each request and open a Goroutine to service the request Go C.serve ()
6 read the contents of each request W, err: = C.readrequest ()
7 determine if the header is empty, if not set handler (this example does not set handler), handler is set to Defaultservemux
8 Calling Handler's Servehttp
9 In this example, the following goes into the Defaultservermux.servehttp
10 Select handler according to request and enter into this handler servehttp
Mux.handler (R). Servehttp (W, R)
11 Select handler:
A determine if there is a route to satisfy this request (looping through Servermux's muxentry)
B If there is a route to satisfy, call this route handler Servehttp
C If no route is met, call Notfoundhandler's servehttp
Take a look at the introduction of this article: http://www.cnblogs.com/yjf512/archive/2012/08/22/2650873.html
3. A case of closure of Golang
Package Mainimport "FMT" Func Adder () func (int) int { sum: = 0 return func (x int) int { sum + = x return sum }} Func Main () { pos, neg: = Adder (), adder () for I: = 0; i <; i++ { fmt. Println ( pos (i), neg ( -2*i), ) }}
For the correct result of the above code, you need to understand the global and local variables in the closure, sum is a global variable, and x is a local variable, so it is not wrong.
Operation Result:
0 01-23-66-1210-2015-3021-4228-5636-7245-90
4. Get the various paths of Golang
User's current path:
Os. GETWD ()
Execute program file relative path:
File, _: = Exec. Lookpath (OS. Args[0])
Package Mainimport ( "OS" "Log" "Os/exec" "path") Func main () { file, _: = OS. GETWD () log. Println ("Current path:", file) file, _ = Exec. Lookpath (OS. Args[0]) log. PRINTLN ("Exec path:", file) dir,_: = path. Split (file) log. Println ("Exec folder relative path:", dir) os. Chdir (dir) wd, _: = OS. GETWD () log. Println ("Exec folder absolute path:", WD)}
Executable file I put in/home/lm/handcode/test
The path I'm executing is/home/lm/.
[Lm@openstack ~]$ handcode/test2013/02/06 11:09:07 current path:/home/lm2013/02/06 11:09:07 exec path:handcode/ test2013/02/06 11:09:07 exec folder relative path:handcode/2013/02/06 11:09:07 exec folder absolute path:/home/lm/handco De
5. Golang error ()
You can define your own error (), String () method for the custom object to output the specified information:
Package Mainimport ("FMT" "math") type errnegativesqrt Float64func (e errnegativesqrt) Error () string {return ' cannot Sqrt n Egative Number: "+ FMT. Sprint (Float64 (e))}func Sqrt (f float64) (Float64, error) {if f < 0 {return 0, errnegativesqrt (f)}z: = float64 (1) for {y : = Z-(z*z-f)/(2*z) if math. Abs (y-z) < 1e-10 {return y, nil}z = Y}return Z, nil}func main () {FMT. Println (SQRT (2)) fmt. Println (Sqrt (-2))}
When F<0, the F is explicitly converted into an The errnegativesqrt type, which is passed to error, invokes the custom Errnegativesqrt error () method.
6. Golang to import your own package
Previously written go programs are in the main package, even if there are multiple go files, which begin with the package main, so they belong to the main packet. Today we experimented with other custom packages of imports: Defined Fsnotify.go and Fsnotify_linux.go, which are two files belonging to the package fsnotify; Main.go will call the method in the Fsnotify package, then how to import the Fsnotify package?
When the Fsnotify package is not imported correctly, the following error is indicated:
[Root@localhost src]# Go build main.gomain.go:5:5:cannot Find package ' fsnotify ' in any of:/software/go/src/pkg/fsnotify (from $GOROOT)/software/fsnotify/src/fsnotify (from $GOPATH)
That is, in the Main.go import "fsnotify" first according to $goroot find, if can not find again according to $gopath find, still can not find the words prompt above error. Run go ENV first to see the environment variables for go:
[Root@localhost software]# go envgoarch= "amd64" gobin= "" gochar= "6" goexe= "" gohostarch= "AMD64" gohostos= "Linux" goos= " Linux "gopath="/software/fsnotify "gorace=" "goroot="/software/go "gotooldir="/software/go/pkg/tool/linux_amd64 " term= "dumb" cc= "gcc" gogccflags= "-g-o2-fpic-m64-pthread" cxx= "g++" cgo_enabled= "1"
So it's a good idea to create a folder with the same name as the custom package under $goroot/src/pkg, and then put the file in this folder, or create a folder with the same name as the custom package under $GOPATH/SRC, and put the file in it, OK. In general, the second approach is used.
$GOPATH can define multiple paths, as is the case with $path, you can define $gopath in/ROOT/.BASHRC:
Gopath=/software/fsnotify:/software/tmpexport Gopath
Then put the previous Fsnotify folder MV to/SOFTWARE/TMP/SRC, go build main.go still successful, the above two points are verified.
7. Golang's project directory structure
In general, a go project will have the following 3 directories under $gopath:
--bin--pkg--src
Where the bin holds the compiled executable file, the PKG holds the compiled package file, and SRC holds the project source file. The general bin and Pkg directories can not be created, and the Go command will be created automatically (like go install), just to create the SRC directory. For the PKG directory, the files in the pkg are generated by go compilation, rather than manually put in. (General file suffix. A) for the SRC directory, where the source files are stored, the go source file is organized in the form of a package. In general, creating a new package creates a new folder in the SRC directory.
For example, to create a new go project named Test, the initial directory is as follows:
Test/|--install|--src
The install content is as follows:
#!/usr/bin/env Bashif [!-f Install]; Thenecho ' Install must is run within its container folder ' 1>&2exit 1ficurdir= ' pwd ' oldgopath= ' $GOPATH ' export Gopat H= "$CURDIR" gofmt-w srcgo install testexport gopath= "$OLDGOPATH" Echo ' finished '
Add this install, do not configure Gopath (avoid adding a go project will add a path to the Gopath)
Next, add a package: Config and a main program. The directory structure is as follows:
test|--install '--src |--config | '--config.go '--Test '--main.go
Note the package name in Config.go is best consistent with the directory config, and the file name can be random. Main.go represents the main package, and the file name is suggested as Main.go. (Note: When inconsistent, the resulting. A file name and directory name are the same, so that when you import, it should be the directory name, and the package name is required when the package is referenced.) For example, if the directory is myconfig and the package name is config, then the production static package file is: MYCONFIG.A, referencing the package: import "Myconfig", using the package Member: CONFIG. Loadconfig ())
Config.go Code:
Package Configfunc Loadconfig () {}
Main.go Code:
Package Mainimport ("config" "FMT") func main () {config. Loadconfig () fmt. Println ("Hello, go!")}
Executed at the project root./install
The directory structure at this time is:
test|--bin| '--test|--install|--pkg| '--linux_amd64| '--config.a '--src |--config | '--config.go '--Test '--main.go
Where CONFIG.A is generated after the package config is compiled; bin/test is a binary file that is generated
This time can be carried out: Bin/test. Will output: Hello, go!
Packages can be multi-layered directory, such as: Net/http package, indicating that the source file under the Src/net/http directory, but the package name in the source file is the name of the last directory, such as HTTP
When you import a package, you must complete the path, such as: Import "Net/http".
The difference between go build and go install:
Go BUILD: Creates a package-compiled binary file in a temporary directory that does not install binaries to the bin, pkg directory, and then directly to the file name that needs to be compiled after the go build.
Go install: The same as the go build parameter, the only difference is to copy the results of the compilation to the bin, the PKG directory, go install need to create a directory with the same name as the project catalog, and then put the main.go in; Go install the project directory name.