第二章 Go Web 開發基礎
2.1第一個Go Web 程序
package mainimport ("fmt""net/http"
)func hello(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello World")
}
func main() {server := &http.Server{Addr: "0.0.0.0:80",}http.HandleFunc("/", hello)server.ListenAndServe()
}
訪問瀏覽器的127.0.0.1:80
接下來我們通過Go語言來創建GET、POST、PUT、DELETE這4種類型的窖戶端請求,來初步了解害戶端的創建方法.
創建GET請求
package mainimport ("fmt""io/ioutil""net/http"
)func main() {resp, err := http.Get("https://www.baidu.com")if err != nil {fmt.Println("err", err)}closer := resp.Bodybytes, err := ioutil.ReadAll(closer)fmt.Println(string(bytes))
}
通過上面的代碼可以獲得百度首頁的HTML文檔
創建POST請求
package mainimport ("bytes""fmt""io/ioutil""net/http"
)func main() {url := "https://www.shirdon.com/comment/add"body := "{\"userId\":1,\"articleId\":1,\"comment\":\"這是一條評論\"}"response, err := http.Post(url, "application/x-www-form-urlencoded", bytes.NewBufferString(body))if err != nil {fmt.Println("err", err)}b, err := ioutil.ReadAll(response.Body)fmt.Println(string(b))
}
?