介紹
HTTPS (Secure Hypertext Transfer Protocol)安全超文本傳輸協議,是一個安全通信通道,它基于HTTP開發用于在客戶計算機和服務器之間交換信息。它使用安全套接字層(SSL)進行信息交換,簡單來說它是HTTP的安全版,是使用TLS/SSL加密的HTTP協議。
HTTP和HTTPS的區別
- HTTPS是加密傳輸協議,HTTP是名文傳輸協議
- HTTPS需要用到SSL證書,而HTTP不用
- HTTPS比HTTP更加安全,對搜索引擎更友好,利于SEO
- HTTPS標準端口443,HTTP標準端口80
- HTTPS基于傳輸層,HTTP基于應用層
- HTTPS在瀏覽器顯示綠色安全鎖,HTTP沒有顯示
1.證書可以認為就是公鑰;
2.在Https通信中,需要CA認證中心的證書以及服務器的證書和私鑰;
3.服務器的證書是用來發送給客戶端的;
4.CA認證中心的證書需要安裝在客戶機上,用來驗證服務器證書的真實性
http server端
http 服務器
package main
import (
"log"
"net/http"
"time"
)
func main() {
// 創建路由器
mux := http.NewServeMux()
// 設置路由規則
mux.HandleFunc("/hello", sayHello)
// 創建服務器
server := http.Server{
Addr: ":1210",
WriteTimeout: time.Second * 3,
Handler: mux,
}
// 監聽端口并提供服務
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"))
}
啟動服務器
$ 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
如上所示:這就是我們服務端返回的內容 hello hello, this is httpserver
http 客戶端
為什么需要客戶端
在多項目、微服務的場景下,項目服務之間的互相通信并不像。使用瀏覽器、命令行輸入域名返回結果。所以需要自己編寫發起 http 請求的客戶端,實現項目服務之間的通信
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
func main() {
// 創建連擊池
transport := http.Transport{
DialContext: (net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100, // 最大空閑連接數
IdleConnTimeout: 90 * time.Second, // 空閑超時時間
TLSHandshakeTimeout: 10 * time.Second, // tls 握手超時時間
ExpectContinueTimeout: 1 * time.Second, // 100-continue狀態碼超時時間
}
// 創建客戶端
client := http.Client{
Transport: transport,
Timeout: 30 * time.Second, // 沒餓
}
// 請求數據
resp, err := client.Get("http://localhost:1210/hello")
if err != nil {
panic(err)
}
defer resp.Body.Close()
// 讀取數據
bds, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bds))
}
運行服務測試一下go run demo/base/http/server/server.go,返回 服務端響應內容 hello hello, this is httpserver
到此這篇關于Golang簡單實現http的server端和client端的文章就介紹到這了,更多相關golang http client 和server 內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- [Asp.Net Core]用Blazor Server Side實現圖片驗證碼
- [Asp.Net Core] 淺談Blazor Server Side
- Ant Design Blazor 組件庫的路由復用多標簽頁功能
- HTTP中header頭部信息詳解
- IOS利用CocoaHttpServer搭建手機本地服務器
- Golang實現http server提供壓縮文件下載功能
- 在Golang中使用http.FileServer返回靜態文件的操作
- 基于http.server搭建局域網服務器過程解析
- golang的httpserver優雅重啟方法詳解
- Blazor Server 應用程序中進行 HTTP 請求