It took a week to learn about the file server. I always had to mix it up in some places and sort out what I learned.
I have been studying go for half a month, and I still have many questions about it. I hope you can tell me something wrong.
Note: In the following code, W is of the HTTP. responsewriter type, and R is of the * HTTP. Request type.
1. The meaning of some types should be clarified first:
Handler: Process requests and generate returned interfaces. It is actually an interface.
Servermux: A route, also a handler. Or interface.
Request: the user's request information, used to parse the user's request information, including post, get, Cookie, URL and other information.
Response: The information that the server needs to report to the client.
Responsewriter: The response generation interface. Or Interface
Conn: network connection.
Servermux has a map table. The map key is R. url. String (), and the value records a method. This method is the same as servehttp, also known as handlerfunc. Another method is to register handlerfunc.
Servemux implements the handler interface and acts as the second parameter of HTTP. listenandserve.
The second parameter of HTTP. listenandserve () is the handle interface, which enables you to configure external routers (non-default routers ).
2. Route settings:
(1)
Func foohandler (W, R ){}
HTTP. Handle ("/foo", foohandler) // HTTP. Handle, not HTTP. Handler
(2)
HTTP. handlefunc ("/foo", func (W, R ){
// Process
})
The above configuration is the default route
If you use servemux as the route, you must use other configuration methods.
(3) configure the servemux route
1)
MUX: = http. newservemux ()
MUX. Handle ("/foo", & foohandler {}) // The second parameter is a handler, which can be a handler interface or a function that returns handler. For example, stripprefix (prefix string, H handler) handler.
Type foohandler struct {}
Func (* foohandler) servehttp (W, R ){
// Process
}
2)
MUX: = http. newservemux ()
MUX. handlefunc ("/foo", foohandler)
Func foohandler (W, R ){
// Process
}
3)
VaR MUX map [String] func (W, R)
MUX = make [String] func (W, R)
MUX ["/foo"] = foohandler
Func foohandler (W, R ){
}
Define another handler as the default handler to implement routing
Type myhandler struct {}
Func (* myhandler) servehttp (W, R ){
If H, OK: = MUX [R. url. String ()]; OK {// pay attention to MUX [] matching. If necessary, use the path package. For example, I use MUX [path. dir (R. url. Path)].
H (W, R)
Return
}
}
Server:
Server: = http. Server {
ADDR: ": 9090 ",
Handler: & myhandler {}, // myhandler is used here
Readtimeout: 5 * time. Second,
}
3. Three Methods for simple file server implementation
(1)
1 package main 2 3 Import (4 "FMT" 5 "log" 6 "net/HTTP" 7) 8 9 func sayhello (w http. responsewriter, R * HTTP. request) {10 FMT. fprintf (W, "% v", "Hello, this is from fileserver1.") // output to client 11} 12 func main () {13 HTTP. handlefunc ("/", sayhello) 14 err: = http. listenandserve (": 9090", nil) // use the default handler = defaultservemux15 if Err! = Nil {16 log. Fatal ("listenandserve:", err) 17} 18}Fileserver1
(2)
1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 ) 8 9 type myhandler struct {10 }11 12 func sayHello(w http.ResponseWriter, r *http.Request) {13 fmt.Fprintf(w, "%v", "Hello,this is from FileServer2.")14 }15 func (*myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {16 fmt.Fprintf(w, "%v", "Bye,this is from FileServer2.")17 }18 19 func main() {20 mux := http.NewServeMux()21 mux.Handle("/b", &myhandler{})22 mux.HandleFunc("/", sayHello)23 err := http.ListenAndServe(":9090", mux)24 if err != nil {25 log.Fatal("ListenAndServe: ", err)26 }27 }View code
(3)
1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "time" 8 ) 9 10 type myhandler struct {11 }12 13 var mux map[string]func(http.ResponseWriter, *http.Request)14 15 func sayHello(w http.ResponseWriter, r *http.Request) {16 fmt.Fprintf(w, "%v", "Hello,this is from FileServer3.")17 }18 func (*myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {19 if h, ok := mux[r.URL.String()]; ok {20 h(w, r)21 return22 }23 }24 25 func main() {26 server := http.Server{27 Addr: ":9090",28 Handler: &myhandler{},29 ReadTimeout: 5 * time.Second,30 }31 mux = make(map[string]func(http.ResponseWriter, *http.Request))32 mux["/"] = sayHello33 err := server.ListenAndServe()34 if err != nil {35 log.Fatal("ListenAndServe: ", err)36 }37 }View code
Golang File Server Summary