<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # 15.2 一個簡單的web服務器 Http是一個比tcp更高級的協議,它描述了客戶端瀏覽器如何與網頁服務器進行通信。Go有自己的`net/http`包,我們來看看它。我們從一些簡單的示例開始, 首先編寫一個“Hello world!”:[查看示例15.6](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_15/hello_world_webserver.go) 我們引入了`http`包并啟動了網頁服務器,和15.1的`net.Listen("tcp", "localhost:50000")`函數的tcp服務器是類似的,使用`http.ListenAndServe("localhost:8080", nil)`函數,如果成功會返回空,否則會返回一個錯誤(可以指定localhost為其他地址,8080是指定的端口號) `http.URL`描述了web服務器的地址,內含存放了url字符串的`Path`屬性;`http.Request`描述了客戶端請求,內含一個`URL`屬性 如果`req`請求是一個POST類型的html表單,“var1”就是html表單中一個輸入屬性的名稱,然后用戶輸入的值就可以通過GO代碼:`req.FormValue("var1")`獲取到(請看[章節15.4](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/15.4.md))。還有一種方法就是先執行`request.ParseForm()`然后再獲取`request.Form\["var1"\]的第一個返回參數,就像這樣: ``` var1, found := request.Form["var1"] ``` 第二個參數`found`就是`true`,如果`var1`并未出現在表單中,`found`就是`false` 表單屬性實際上是一個`map[string][]string`類型。網頁服務器返回了一個`http.Response`,它是通過`http.ResponseWriter`對象輸出的,這個對象整合了HTTP服務器的返回結果;通過對它寫入內容,我們就講數據發送給了HTTP客戶端。 現在我們還需要編寫網頁服務器必須執行的程序,它是如何處理請求的呢。這是在`http.HandleFunc`函數中完成的,就是在這個例子中當根路徑“/”(url地址是[http://localhost:8080)被請求的時候(或者這個服務器上的其他地址),`HelloServer`函數就被執行了。這個函數是`http.HandlerFunc`類型的,它們通常用使用Prehandler來命名,在前邊加了一個Pref前綴。](http://localhost:8080%EF%BC%89%E8%A2%AB%E8%AF%B7%E6%B1%82%E7%9A%84%E6%97%B6%E5%80%99%EF%BC%88%E6%88%96%E8%80%85%E8%BF%99%E4%B8%AA%E6%9C%8D%E5%8A%A1%E5%99%A8%E4%B8%8A%E7%9A%84%E5%85%B6%E4%BB%96%E5%9C%B0%E5%9D%80%EF%BC%89%EF%BC%8C%60HelloServer%60%E5%87%BD%E6%95%B0%E5%B0%B1%E8%A2%AB%E6%89%A7%E8%A1%8C%E4%BA%86%E3%80%82%E8%BF%99%E4%B8%AA%E5%87%BD%E6%95%B0%E6%98%AF%60http.HandlerFunc%60%E7%B1%BB%E5%9E%8B%E7%9A%84%EF%BC%8C%E5%AE%83%E4%BB%AC%E9%80%9A%E5%B8%B8%E7%94%A8%E4%BD%BF%E7%94%A8Prehandler%E6%9D%A5%E5%91%BD%E5%90%8D%EF%BC%8C%E5%9C%A8%E5%89%8D%E8%BE%B9%E5%8A%A0%E4%BA%86%E4%B8%80%E4%B8%AAPref%E5%89%8D%E7%BC%80%E3%80%82) `http.HandleFunc`注冊了一個處理函數(這里是`HelloServer`)來處理對應`/`的請求。 `/`可以被替換為其他特定的url比如`/create`,`/edit`等等;你可以為每一個特定的url定義一個單獨的處理函數。這個函數需要兩個參數:第一個是`ReponseWriter`類型的`w`;第二個是請求`req`。程序向`w`寫入了`Hello`和`r.URL.Path[1:]`組成的字符串后邊的`[1:]`表示“創建一個從第一個字符到結尾的子切片”,用來丟棄掉路徑開頭的“/”,`fmt.Fprintf()`函數完成了本次寫入(請看[章節12.8](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/12.8.md));另外一種寫法是`io.WriteString(w, "hello, world!\n")` 總結:第一個參數是請求的路徑,第二個參數是處理這個路徑請求的函數的引用。 示例 15.6 [hello\_world\_webserver.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_15/hello_world_webserver.go): ``` package main import ( "fmt" "log" "net/http" ) func HelloServer(w http.ResponseWriter, req *http.Request) { fmt.Println("Inside HelloServer handler") fmt.Fprintf(w, "Hello,"+req.URL.Path[1:]) } func main() { http.HandleFunc("/", HelloServer) err := http.ListenAndServe("localhost:8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } } ``` 使用命令行啟動程序,會打開一個命令窗口顯示如下文字: ``` Starting Process E:/Go/GoBoek/code_examples/chapter_14/hello_world_webserver.exe ... ``` 然后打開你的瀏覽器并輸入url地址:`http://localhost:8080/world`,瀏覽器就會出現文字:`Hello, world`,網頁服務器會響應你在`:8080/`后邊輸入的內容 使用`fmt.Println`在控制臺打印狀態,在每個handler被請求的時候,在他們內部打印日志會很有幫助 注: 1)前兩行(沒有錯誤處理代碼)可以替換成以下寫法: ``` http.ListenAndServe(":8080", http.HandlerFunc(HelloServer)) ``` 2)`fmt.Fprint`和`fmt.Fprintf`都是用來寫入`http.ResponseWriter`的不錯的函數(他們實現了`io.Writer`)。 比如我們可以使用 ``` fmt.Fprintf(w, "<h1>%s<h1><div>%s</div>", title, body) ``` 來構建一個非常簡單的網頁并插入`title`和`body`的值 如果你需要更多復雜的替換,使用模板包(請看[章節15.7](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/15.7.md)) 3)如果你需要使用安全的https連接,使用`http.ListenAndServeTLS()`代替`http.ListenAndServe()` 4)`http.HandleFunc("/", Hfunc)`中的`HFunc`是一個處理函數,如下: ``` func HFunc(w http.ResponseWriter, req *http.Request) { ... } ``` 也可以使用這種方式:`http.Handle("/", http.HandlerFunc(HFunc))` 上邊的`HandlerFunc`只是一個類型名稱,它定義如下: ``` type HandlerFunc func(ResponseWriter, *Request) ``` 它是一個可以把普通的函數當做HTPP處理器的適配器。如果`f`函數聲明的合適,`HandlerFunc(f)`就是一個執行了`f`函數的處理器對象。 `http.Handle`的第二個參數也可以是`T`的一個obj對象:`http.Handle("/", obj)`給T提供了`SereHTTP`方法,實現了http的`Handler`接口: ``` func (obj *Typ) ServeHTTP(w http.ResponseWriter, req *http.Request) { ... } ``` 這個用法在[章節15.8](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/15.8.md)類型`Counter`和`Chan`上使用過。只要實現了`http.Handler`,`http`包就可以處理任何HTTP請求。 練習 15.2:[webhello2.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_15/webhello2.go) 編寫一個網頁服務器監聽端口9999,有如下處理函數: - 當請求`http://localhost:9999/hello/Name`時,響應:`hello Name`(Name需是一個合法的姓,比如Chris或者Madeleine) - 當請求`http://localhost:9999/shouthello/Name`時,響應:`hello NAME` 練習 15.3:[hello\_server.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_15/hello_server.go) 創建一個空結構`hello`并使它實現`http.Handler`。運行并測試。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看