天天看點

快速搭建HTTP伺服器 go http server

go http server 例子,自定義路由。

package main

import (
    "fmt"
    "net/http"
    "reflect"
    "strings"
)

func hello(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Hello"))
}

type Handlers struct {
}

func (h *Handlers) ResAction(w http.ResponseWriter, req *http.Request) {
    fmt.Println("res")
    w.Write([]byte("res"))
}

func say(w http.ResponseWriter, req *http.Request) {
    pathInfo := strings.Trim(req.URL.Path, "/")
    fmt.Println("pathInfo:", pathInfo)

    parts := strings.Split(pathInfo, "/")
    fmt.Println("parts:", parts)

    var action = "ResAction"
    fmt.Println(strings.Join(parts, "|"))
    if len(parts) > 1 {
        fmt.Println("22222222")
        action = strings.Title(parts[1]) + "Action"
    }
    fmt.Println("action:", action)
    handle := &Handlers{}
    controller := reflect.ValueOf(handle)
    method := controller.MethodByName(action)
    r := reflect.ValueOf(req)
    wr := reflect.ValueOf(w)
    method.Call([]reflect.Value{wr, r})
}

func main() {
    http.HandleFunc("/hello", hello)
    http.Handle("/handle/", http.HandlerFunc(say))
    http.ListenAndServe(":8001", nil)
    //select {} //阻塞程序
}      

通路:http://127.0.0.1:8001/handle/res

快速搭建HTTP伺服器 go http server
package main

import (
    "io"
    "net/http"
    "log"
)

// hello world, the web server
func 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伺服器端程式。

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.