GO http

weixin_34320159發表於2017-02-06

在Golang中寫一個http web伺服器大致是有兩種方法:

1 使用net包的net.Listen來對埠進行監聽

2 使用net/http包

先看到的是Get,Post,PostForm三個函式。這三個函式直接實現了http客戶端

import (
"fmt"
"net/http"
"io/ioutil"
)

func main() {
response,_ := http.Get("http://www.baidu.com")
defer response.Body.Close()
body,_ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}

除了使用這三個函式來建立一個簡單客戶端,還可以使用:
http.Client和http.NewRequest來模擬請求

package main

import (
"net/http"
"io/ioutil"
"fmt"
)

func main() {
client := &http.Client{}
reqest, _ := http.NewRequest("GET", "http://www.baidu.com", nil)

reqest.Header.Set("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
reqest.Header.Set("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3")
reqest.Header.Set("Accept-Encoding","gzip,deflate,sdch")
reqest.Header.Set("Accept-Language","zh-CN,zh;q=0.8")
reqest.Header.Set("Cache-Control","max-age=0")
reqest.Header.Set("Connection","keep-alive")
 
response,_ := client.Do(reqest)
if response.StatusCode == 200 {
    body, _ := ioutil.ReadAll(response.Body)
    bodystr := string(body);
    fmt.Println(bodystr)
}

}

http包封裝地非常bt,只需要兩行!!:

package main

import (
"net/http"
)

func SayHello(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello"))
}

func main() {
http.HandleFunc("/hello", SayHello)
http.ListenAndServe(":8001", nil)

}

進行埠的監聽:http.ListenAndServe(":8001", nil)

註冊路徑處理函式:http.HandleFunc("/hello", SayHello)

處理函式:func SayHello(w http.ResponseWriter, req *http.Request)

相關文章