天天看點

go基礎之web應用

Go是一門相對年輕的語言,并且它非常适合用來編寫那些需要快速運作的伺服器端程式。Go擁有非常多的标準庫,許多公司已經開始使用Go了。Go隻需要簡單的幾行就可以建立一個可以運作的web應用。

建立檔案server.go

package main

import (
    "fmt"
    "net/http"
)


func handler(writer http.ResponseWriter, request *http.Request) {
    fmt.Fprintf(writer, "hello world!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8000", nil)
}      

運作go run server.go

打開浏覽器通路http://localhost:8000/,頁面顯示hello world!

http.HandleFunc("/", handler)      

通路根路徑執行handler方法,這個方法帶有2個參數,一個是http.ResponseWriter接口,一個是指向http.Request的指針。Request是擷取通路位址傳遞的參數,ResponseWriter用于響應給用戶端資訊。

http.ListenAndServe(":8000", nil)      

啟動一個8000端口的web服務,這樣一個最簡單的web應用就建立好了。

那如果還有别的通路位址呢?

http.HandleFunc("/", handler)
http.HandleFunc("/api", api)
http.HandleFunc("/hand", hand)
http.ListenAndServe(":8000", nil)      
func api(writer http.ResponseWriter, request *http.Request) {
    fmt.Fprintf(writer, "hello api!")
}
func hand(writer http.ResponseWriter, request *http.Request) {
    fmt.Fprintf(writer, "hello hand!")
}      
server := http.Server{
    Addr: "127.0.0.1:8080",
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
server.ListenAndServe()      

繼續閱讀