Go語言http包簡易入門


說道go語言web編程,必不可少的會使用到net/http包。go語言將web開發需要使用到的很多內容都放在了標准庫中——net/http。

如何寫一個簡單的web程序很容易。如下:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "net/http"
 6 )
 7 
 8 func hello(w http.ResponseWriter, r *http.Request) {
 9     fmt.Fprintf(w, "hello")
10 }
11 
12 func main() {
13     server := &http.Server{
14         Addr: "0.0.0.0:8080",
15     }
16     http.HandleFunc("/hello", hello)
17     server.ListenAndServe()
18 }

其中使用了http包。使用http.HandleFunc就是使用了一個處理器函數。
處理器函數是一個簽名和ServeHTTP方法相同的函數,Go語言中,有一種HandlerFunc函數類型,可以加將這個函數轉化為帶有方法的處理器(Handler)?

ServerMux是一個路由管理器,也可以說是一個多路復用器,使用方式如下:

 1 package main
 2 import (
 3     "fmt"
 4     "net/http"
 5 )
 6 func main() {
 7     servermux := http.NewServeMux()
 8     servermux.HandleFunc("/hello", hello)
 9     server := &http.Server{
10         Addr: ":8080",
11         Handler: servermux,
12     }
13     server.ListenAndServe()
14 }
15 func hello(w http.ResponseWriter, r *http.Request) {
16     fmt.Fprintln(w, "hello world")
17 }

其實是在使用http.HandleFunc的時候,調用了

1 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2     DefaultServeMux.HandleFunc(pattern, handler)
3 }

這樣的話,其實是使用了一個變量DefaultServeMux,再看看這個變量的內容:

1 var DefaultServeMux = &defaultServeMux
2 var defaultServeMux ServeMux

這個變量其實就是ServeMux的實例。也就是ServeMux,所以在使用http的handerfunc的時候,是使用了這個多路復用器的。這個處理器也是默認的處理器。如果沒有聲明或者直接使用其他的處理器的時候,調用處理器函數和處理器都是使用了這個。

 

接下來看HandleFunc這個函數,以上使用的http包的函數HandleFunc最終調用的是ServeMux的HandleFunc。所以在使用的時候Handle和HandleFunc完全一致。

type HandlerFunc func(ResponseWriter, *Request)

HandleFunc最終會將函數轉成HandleFunc,等同於Handler,Handler是一個接口,如下:

1 type Handler interface {
2     ServeHTTP(ResponseWriter, *Request)
3 }

所以其實這兩種類型是等價的。


免責聲明!

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



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