With the application of Go more and more hot, oneself also finally began to study. Usually use C, look at the go is more cordial. All right, here we go.
Today mainly according to the contents of the tree on their own simple practice of the next most basic output, as well as Web features, on the code:
1 Package Main 2 3 Import (4 " FMT " 5 )67func main () {8 FMT. Printf ("Hello world\n")9 }
Addition Operation code:
1 Package Main2 3 Import (4 "FMT"5 )6 7Func Add (AintBint) (cint){8C= A +b9 returnCTen } One A - Func Main () { -C:=add (1,2) the FMT. Println (c) -}
Web page "Hello World" code:
1 Package Main2 3 Import (4 "FMT"5 "net/http"6 )7Func sayhelloname (w http. Responsewriter,r *http. Request) {8Fmt. fprintf (W,"Hello,world")9 Ten } One A Func Main () { - -http. Handlefunc ("/", Sayhelloname) the}
Login:
Web Login Code:
1 Package Main2 3 Import (4 "FMT"5 "html/template"6 "net/http"7 "Log"8 )9 TenFunc Login (w http. responsewriter,r*http. Request) { One AFmt. Println ("Method:", R.method) - ifR.method = ="GET"{ -T,_:=template. Parsefiles ("/USERS/MAC/IDEAPROJECTS/GO1/LOGIN.GTPL") the T.execute (W,nil) -}Else{ - R.parseform () -Fmt. Println ("Username:", r.form["username"]) +Fmt. Println ("Password", r.form["Password"]) - } + } A at Func Main () { -http. Handlefunc ("/login", login) -Err:=http. Listenandserve (": 9090", nil) - ifErr! =Nil { -Log. Fatal ("Listenandserve:", Err) - } in}
Operation Result:
Consle:
Note here that the program in the MAC environment, the page template path needs to use the absolute path "/USERS/MAC/IDEAPROJECTS/GO1/LOGIN.GTPL", or the following error will be reported:
Runtime Error:invalid memory address or nil pointer dereference goroutine 5
Go Learning Notes (i)