HTTPS (Secure Hypertext Transfer Protocol)安全超文本傳輸協(xié)議,是一個安全通信通道,它基于HTTP開發(fā)用于在客戶計算機和服務(wù)器之間交換信息。它使用安全套接字層(SSL)進行信息交換,簡單來說它是HTTP的安全版,是使用TLS/SSL加密的HTTP協(xié)議。
HTTP和HTTPS的區(qū)別
1.證書可以認為就是公鑰;
2.在Https通信中,需要CA認證中心的證書以及服務(wù)器的證書和私鑰;
3.服務(wù)器的證書是用來發(fā)送給客戶端的;
4.CA認證中心的證書需要安裝在客戶機上,用來驗證服務(wù)器證書的真實性
http 服務(wù)器
package main import ( "log" "net/http" "time" ) func main() { // 創(chuàng)建路由器 mux := http.NewServeMux() // 設(shè)置路由規(guī)則 mux.HandleFunc("/hello", sayHello) // 創(chuàng)建服務(wù)器 server := http.Server{ Addr: ":1210", WriteTimeout: time.Second * 3, Handler: mux, } // 監(jiān)聽端口并提供服務(wù) log.Println("starting httpserver at http:localhost:1210") log.Fatal(server.ListenAndServe()) } func sayHello(w http.ResponseWriter, r *http.Request) { time.Sleep(1 * time.Second) w.Write([]byte("hello hello, this is httpserver")) }
啟動服務(wù)器
$ go run demo/base/http/server/server.go 2021/05/31 22:26:35 starting httpserver at http:localhost:1210
使用 瀏覽器 或者 命令行測試一下:
$ curl -v http://localhost:1210/hello * Trying ::1:1210... * Connected to localhost (::1) port 1210 (#0) > GET /hello HTTP/1.1 > Host: localhost:1210 > User-Agent: curl/7.69.1 > Accept: */* > * Mark bundle as not supporting multiuse HTTP/1.1 200 OK Date: Mon, 31 May 2021 14:28:28 GMT Content-Length: 31 Content-Type: text/plain; charset=utf-8 * Connection #0 to host localhost left intact hello hello, this is httpserver
如上所示:這就是我們服務(wù)端返回的內(nèi)容 hello hello, this is httpserver
在多項目、微服務(wù)的場景下,項目服務(wù)之間的互相通信并不像。使用瀏覽器、命令行輸入域名返回結(jié)果。所以需要自己編寫發(fā)起 http 請求的客戶端,實現(xiàn)項目服務(wù)之間的通信
package main import ( "fmt" "io/ioutil" "net" "net/http" "time" ) func main() { // 創(chuàng)建連擊池 transport := http.Transport{ DialContext: (net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, MaxIdleConns: 100, // 最大空閑連接數(shù) IdleConnTimeout: 90 * time.Second, // 空閑超時時間 TLSHandshakeTimeout: 10 * time.Second, // tls 握手超時時間 ExpectContinueTimeout: 1 * time.Second, // 100-continue狀態(tài)碼超時時間 } // 創(chuàng)建客戶端 client := http.Client{ Transport: transport, Timeout: 30 * time.Second, // 沒餓 } // 請求數(shù)據(jù) resp, err := client.Get("http://localhost:1210/hello") if err != nil { panic(err) } defer resp.Body.Close() // 讀取數(shù)據(jù) bds, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(bds)) }
運行服務(wù)測試一下go run demo/base/http/server/server.go,返回 服務(wù)端響應(yīng)內(nèi)容 hello hello, this is httpserver
到此這篇關(guān)于Golang簡單實現(xiàn)http的server端和client端的文章就介紹到這了,更多相關(guān)golang http client 和server 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:黑龍江 嘉峪關(guān) 武漢 新余 江西 張掖 延邊 宜賓
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Golang簡單實現(xiàn)http的server端和client端》,本文關(guān)鍵詞 Golang,簡單,實現(xiàn),http,的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。