快速搭建HTTP服务器 go http server - Go语言中文社区

快速搭建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


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.



版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/chenxun2009/article/details/73862810
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-25 11:43:40
  • 阅读 ( 1939 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢