1.golang print輸入
package main import "fmt" func main() { fmt.Printf("Hello World!\n") }
執行以下命令
go build print.gogolang
2. go web 服務端
Go語言標準庫 - net/http
Go Web服務器的搭建就須要用到Go語言官方提供的標準庫 net/http
,經過http包提供了HTTP客戶端和服務端的實現。同時使用這個包能很簡單地對web的路由,靜態文件,模版,cookie等數據進行設置和操做。web
http包創建Web服務器
package main import ( "fmt" "net/http" "strings" "log" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析參數,默認是不會解析的 fmt.Println(r.Form) //這些信息是輸出到服務器端的打印信息 fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello Wrold!") //這個寫入到w的是輸出到客戶端的 } func main() { http.HandleFunc("/", sayhelloName) //設置訪問的路由 err := http.ListenAndServe(":9090", nil) //設置監聽的端口 if err != nil { log.Fatal("ListenAndServe: ", err) } }
上面的代碼咱們在IDE中編譯後並運行成功後,這個時侯咱們就能夠在9090端口監聽http連接請求了。瀏覽器
們在瀏覽器中輸入了 http://ip:9090,能夠看到瀏覽器頁面中輸入出 Hello World!
這個時侯若是咱們在瀏覽器地址後面加一些參數試試:http://ip:9090?url_long=111&url_long=222,服務器
看看瀏覽器中輸出什麼?服務器端輸出的又是什麼?cookie
map[url_long:[111 222]] path / scheme [111 222] key: url_long val: 111222
咱們看到了上面的代碼,要編寫一個Web服務器是否是很簡單,只要調用http包的兩個函數就能夠了。
咱們看到Go經過簡單的幾行代碼就已經運行起來一個Web服務了,並且這個Web服務內部有支持高併發的特性。併發