這篇文章將為大家詳細講解有關(guān)go語言中http的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
我們提供的服務有:網(wǎng)站設計制作、成都做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、臨泉ssl等。為上千余家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術(shù)的臨泉網(wǎng)站制作公司
1、net/http 包提供的 http.ListenAndServe() 方法,在指定的地址監(jiān)聽
該方法用于在指定的 TCP 網(wǎng)絡地址 addr 進行監(jiān)聽,然后調(diào)用服務端處理程序來處理傳入的連 接請求。該方法有兩個參數(shù):第一個參數(shù) addr 即監(jiān)聽地址;第二個參數(shù)表示服務端處理程序, 通常為空,這意味著服務端調(diào)用 http.DefaultServeMux 進行處理,而服務端編寫的業(yè)務邏 輯處理程序 http.Handle() 或 http.HandleFunc() 默認注入 http.DefaultServeMux 中。
2.處理https請求
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error
3.路由
http.HandleFunc()方法接受兩個參數(shù)
第一個參數(shù)是HTTP請求的 目標路徑"/hello",該參數(shù)值可以是字符串,也可以是字符串形式的正則表達式
第二個參數(shù)指定具體的回調(diào)方法,比如helloHandler。
當我們的程序運行起來后,訪問http://localhost:8080/hello , 程序就會去調(diào)用helloHandler()方法中的業(yè)務邏輯程序。
4.get/post訪問
resp, err := http.Get("...")
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))resp, err:=http.Post(“.....”, ”application/x-www-form-urlencoded”, strings.NewReader(“..=...”)) defer resp.Body.Close() body,err:=ioutil.ReadAll(resp.Body) fmt.Println(string(body))
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
//模擬一個post提交請求
resp, err := http.Post("http://www.baidu.com", "application/x-www-form-urlencoded", strings.NewReader("id=1"))
if err != nil {
panic(err)
}
//關(guān)閉連接
defer resp.Body.Close()
//讀取報文中所有內(nèi)容
body, err := ioutil.ReadAll(resp.Body)
//輸出內(nèi)容
fmt.Println(string(body))
}模擬一個http server 監(jiān)聽地址:127.0.0.1:8080
// http_server.go
package main
import (
//"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world!"))
})
http.ListenAndServe("127.0.0.1:8080", nil)
}
關(guān)于“go語言中http的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文名稱:go語言中http的示例分析
網(wǎng)站地址:http://chinadenli.net/article8/jhjpop.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、商城網(wǎng)站、營銷型網(wǎng)站建設、品牌網(wǎng)站建設、微信公眾號、用戶體驗
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)