Go http server

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport (    "io"    "net/http"    "log")// hello world, the web serverfunc HelloServer(w http.ResponseWriter, req *http.Request) {    io.WriteString(w, "hello, world!\n")}func main() {    http.HandleFunc("/hello", HelloServer)    err := http.ListenAndServe(":12345", nil)    if err != nil {        log.Fatal("ListenAndServe: ", err)    }}

上面是一個簡單的go http伺服器端程式。 受此代碼影響,在看martini代碼的時候,一直在試圖尋找調用http.HandleFunc的代碼,一直找不到。。

http.ListenAndServe的原型:

func ListenAndServe(addr string, handler Handler) error

上面例子中,Handler傳遞的是nil。再看Handler原型:
type Handler interface {    ServeHTTP(ResponseWriter, *Request)}
而martini就是實現了Handler的對象!
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {    m.createContext(res, req).run()}

 

再看Go 語言編程裡關於ListenAndServe介紹:

該方法用於在指定的TCP 網路地址addr 進行監聽,然後調用服務端處理常式來處理傳入的連
接請求。該方法有兩個參數:第一個參數addr 即監聽地址;第二個參數表示服務端處理常式,
通常為空白,這意味著服務端調用 http.DefaultServeMux 進行處理,而服務端編寫的業務邏
輯處理常式 http.Handle() 或 http.HandleFunc() 預設注入 http.DefaultServeMux 中,
具體代碼如下:

http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {   fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))   }) log.Fatal(http.ListenAndServe(":8080", nil)) 

如果想更多地控制服務端的行為,可以自訂 http.Server,代碼如下:

s := &http.Server{     Addr: ":8080",     Handler: myHandler,     ReadTimeout: 10 * time.Second,     WriteTimeout: 10 * time.Second,     MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe())

 

type Server struct {    Addr           string        // TCP address to listen on, ":http" if empty    Handler        Handler       // handler to invoke, http.DefaultServeMux if nil    ReadTimeout    time.Duration // maximum duration before timing out read of the request    WriteTimeout   time.Duration // maximum duration before timing out write of the response    MaxHeaderBytes int           // maximum size of request headers, DefaultMaxHeaderBytes if 0    TLSConfig      *tls.Config   // optional TLS config, used by ListenAndServeTLS    // TLSNextProto optionally specifies a function to take over    // ownership of the provided TLS connection when an NPN    // protocol upgrade has occurred.  The map key is the protocol    // name negotiated. The Handler argument should be used to    // handle HTTP requests and will initialize the Request's TLS    // and RemoteAddr if not already set.  The connection is    // automatically closed when the function returns.    TLSNextProto map[string]func(*Server, *tls.Conn, Handler)    // ConnState specifies an optional callback function that is    // called when a client connection changes state. See the    // ConnState type and associated constants for details.    ConnState func(net.Conn, ConnState)    // ErrorLog specifies an optional logger for errors accepting    // connections and unexpected behavior from handlers.    // If nil, logging goes to os.Stderr via the log package's    // standard logger.    ErrorLog *log.Logger    // contains filtered or unexported fields}

 


ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux:http.Handle("/foo", fooHandler)http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))})log.Fatal(http.ListenAndServe(":8080", nil))

 

func Handle

func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically nil, in which case the DefaultServeMux is used.




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.