Creating GoWeb web server

Brief introduction

go provides a set of standard libraries for creating web server and create a server go through the steps as simple as calling ListenAndServe function by net / http packets and incoming network address and is responsible for handling the request processor (handler) as parameters on it. If the network address parameter is an empty string, then the server uses the default 80 if the parameter is the processor; network connection port nil , the server uses the default multiplexer DefaultServeMux, of course, also possible to create a multi-function by calling NewServeMux multiplexers. After multiplexer receives the URL request according to the request of the user to determine which processor is used to process the request, after finding redirected to the corresponding processor to process the request

The default multiplexer (DefaultServeMux)

  1. Function processing using a processor requests
package main

import (
	"fmt"
	"net/http"
)
//创建处理器函数
func handler(w http.ResponseWriter, r *http.Request)  {
	fmt.Fprintln(w, "正在通过处理器函数处理你的请求")
}
func main() {
	http.HandleFunc("/", handler)
	//创建路由
	http.ListenAndServe(":8080", nil)
}
  • func HandleFunc
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc register and a processor function handler corresponding to pattern mode (registered DefaultServeMux). ServeMux document explains the mechanism of pattern matching

The principle function of the processor

  • go have a kind of language HandlerFunc function type, it can be a function with the correct signature f convert Handler with a method of f

type HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

HandlerFunc type is an adapter, let us cast by ordinary functions as HTTP handler can use. If f is a function of having the appropriate signature, HandlerFunc (f) implement the Handler interface by calling f

  1. Using a processor to process the request
package main

import (
	"fmt"
	"net/http"
)

type MyHandler struct {

}

func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "通过自己创建的处理器处理请求!")
}
func main() {
	myHandler := MyHandler{}
	http.Handle("/myHandler", &myHandler)
	http.ListenAndServe(":8080", nil)
}

Browser access
http://127.0.0.1:8080/myHandler

  • func Handle
func Handle(pattern string, handler Handler)

Handle Register HTTP handler and a corresponding processor mode pattern (registered DefaultServeMux). If the pattern has already registered a processor, Handle will panic. ServeMux document explains the mechanism of pattern matching

  • type Handler
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

Handler implements the interface objects can be registered to the HTTP server to provide services to a specific path and its sub-tree

ServeHTTP should reply header fields and data write interfaces ResponseWriter then returns. Marking the return request has ended, HTTP server can be transferred to the next request on the connection

As long as a structure to achieve a ServeHTTP method Handler interface, then it is a processor

  1. A more detailed configuration of the server through Server Architecture
  • type Server
type Server struct {
    Addr           string        // 监听的TCP地址,如果为空字符串会使用":http"
    Handler        Handler       // 调用的处理器,如为nil会调用http.DefaultServeMux
    ReadTimeout    time.Duration // 请求的读取操作在超时前的最大持续时间
    WriteTimeout   time.Duration // 回复的写入操作在超时前的最大持续时间
    MaxHeaderBytes int           // 请求的头域最大长度,如为0则用DefaultMaxHeaderBytes
    TLSConfig      *tls.Config   // 可选的TLS配置,用于ListenAndServeTLS方法
    // TLSNextProto(可选地)指定一个函数来在一个NPN型协议升级出现时接管TLS连接的所有权。
    // 映射的键为商谈的协议名;映射的值为函数,该函数的Handler参数应处理HTTP请求,
    // 并且初始化Handler.ServeHTTP的*Request参数的TLS和RemoteAddr字段(如果未设置)。
    // 连接在函数返回时会自动关闭。
    TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
    // ConnState字段指定一个可选的回调函数,该函数会在一个与客户端的连接改变状态时被调用。
    // 参见ConnState类型和相关常数获取细节。
    ConnState func(net.Conn, ConnState)
    // ErrorLog指定一个可选的日志记录器,用于记录接收连接时的错误和处理器不正常的行为。
    // 如果本字段为nil,日志会通过log包的标准日志记录器写入os.Stderr。
    ErrorLog *log.Logger
    // 内含隐藏或非导出字段
}

Server type defines the parameters of running HTTP server. Zero value for the Server configuration is legitimate

package main

import (
	"fmt"
	"net/http"
	"time"
)

type MyHandler struct {

}

func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "通过详细配置服务器的信息来处理请求!")
}
func main() {
	myHandler := MyHandler{}
	//创建Server结构,并详细配置
	server := http.Server{
		Addr: ":8080",
		Handler: &myHandler,
		ReadTimeout: 2 * time.Second,
	}
	server.ListenAndServe()

}

Create your own using a multiplexer

  1. When creating a server, a multiplexer can also create a method by NewServeMux

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux Creates and returns a new * ServeMux

package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request)  {
	fmt.Fprintln(w, "通过自己创建的多路复用器来处理请求")
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/myMux", handler)
	http.ListenAndServe(":8080", mux)
}

Structure ServeMux

type ServeMux

type ServeMux struct {
    // 内含隐藏或非导出字段
}

ServeMux HTTP request type is a multiplexer. It will be a list of URL patterns with a registered each received request matches, and call and URL that best matches the pattern of the processor.

Mode is fixed, the beginning of the path from the root, such as "/favicon.ico", or the root of a subtree, such as "/ images /" (slash end note). Longer mode takes priority over short mode, so if the pattern "/ images /" and "/ images / thumbnails /" are registered processor, the processor will be used for a path to "/ images / thumbnails /" start request, before receiving a request at the processor a "/ images /" subtree to the remaining path.

Note that because the mode slash ending on behalf of a child from the root of the tree, the pattern "/" will match all the other paths are not registered pattern matching, not just the path "/."

Mode can be (optionally) to start the host name, the path to match only on the host. Specify the host pattern precedence over the general pattern, thus registering a two mode "/ codesearch" and "codesearch.google.com/" processor will not take over the target of "http://www.google.com/" requests.

Harmless URL path ServeMux also notice request, any path will be included. "" Or "..." in the request is redirected to the URL is not equivalent to these two elements. (See path.Clean function)

Structure related method ServeMux

  • func (*ServeMux) Handle
func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle Register HTTP handler and a corresponding processor mode pattern. If the pattern has already registered a processor, Handle will panic.

  • func (* ServeMux) HandleFunc
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc register a function handler and a corresponding processor mode pattern.

  • func (* ServeMux) Handler
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

The Handler r.Method, r.Host r.URL.Path and other data, returned for the HTTP handler processes the request. It always returns a non-nil processor. If the path is not a canonical form it will return to the built-in processor specifications for redirecting the path equivalent.

Handler also returns the request matches the registered pattern; in the case of the built-in processor redirection, pattern will match after redirection. If there is no registered pattern may be applied to the request, the method returns a built-in "404 page not found" mode processor and an empty string.

  • func (*ServeMux) ServeHTTP
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP the request sent to the processor with the requested URL pattern corresponding to the best match

Published 116 original articles · won praise 27 · views 10000 +

Guess you like

Origin blog.csdn.net/wuxingge/article/details/105219923