Go語言_HTTP包


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

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

2 使用net/http包

 

這里是討論如何使用net/http包創建一個web服務器

net/http請求提供了HTTP客戶端和服務端的具體實現

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)
    }
}

clip_image001

 

如何創建web服務端?

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)

 

golang服務器的效率怎樣呢?

看看這個帖子:

http://groups.google.com/group/golang-nuts/browse_thread/thread/cde2cc6278cefc90

node.js is 45% faster than golang(確實傷心)

golang服務端的效率確實沒有node.js高,幾乎是它的一半。但話說回來,如果一些並發量不是很大的site,還是可以使用golang做服務器的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM