原 使用Go語言編寫Web程式(一)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

建立一個 main.go

package mainimport(    "fmt"    "log"    "net/http")func main(){    fmt.Println("服務連接埠:8000") //控制台輸出資訊err := http.ListenAndServe(":8000", nil) //設定監聽的連接埠if err != nil {log.Fatal("ListenAndServe: ", err)}}

使用 go run main.go 執行上面代碼,如果在使用windows系統,我們可以在命令視窗下使用 netstat -aon|findstr "8000"  命令查看連接埠佔用情況,使用tasklist|findstr "PID(例圖中是11492)" 查看使用8000連接埠的應用如:

由於僅是進行了8000連接埠的服務進行偵聽而沒有對URL請求做處理,所以在瀏覽器中開啟http://localhost:8000,只會得到“404 page not found”資訊。

接下來的代碼我們要通過Go的http庫引入URL請求處理。

package mainimport(    "fmt"    "log"    "net/http")func handler(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "歡迎使用Go語言")}func main(){    http.HandleFunc("/", handler)    fmt.Println("服務連接埠:8000") //控制台輸出資訊err := http.ListenAndServe(":8000", nil) //設定監聽的連接埠if err != nil {log.Fatal("ListenAndServe: ", err)}}

當我們重新運行 go run main.go 後,我們通過瀏覽器開啟 http://localhost:8000 時,就可以看到如下資訊:

main函數開始調用了 http.HandleFunc 對 web根節點(“/”)請求使用handler函數進行處理,handler函數使用http.ResponseWriter 和 http.Request 作為參數,http.ResponseWriter值對HTTP服務進行響應處理髮送資料到HTTP用戶端(瀏覽器)。http.Request 是一個由用戶端(瀏覽器)發送的HTTP請求資料結構。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.