File tree 3 files changed +78
-0
lines changed
3 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "io"
5
+ "net/http"
6
+ )
7
+
8
+ func hello (rw http.ResponseWriter , req * http.Request ) {
9
+ io .WriteString (rw , "hello tmpbook" )
10
+ }
11
+
12
+ func main () {
13
+ // HandleFunc 源代码如下
14
+ http .HandleFunc ("/" , hello )
15
+ // 此处省略了错误处理,如果出错会自动退出,比如端口占用
16
+ http .ListenAndServe (":8080" , nil )
17
+ }
18
+
19
+ // func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
20
+ // DefaultServeMux.HandleFunc(pattern, handler)
21
+ // }
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "io"
5
+ "net/http"
6
+ )
7
+
8
+ type MyHandle struct {}
9
+
10
+ func main () {
11
+ mux := http .NewServeMux ()
12
+ mux .Handle ("/" , & MyHandle {})
13
+ http .ListenAndServe (":8080" , mux )
14
+ }
15
+
16
+ func (* MyHandle ) ServeHTTP (w http.ResponseWriter , r * http.Request ) {
17
+ io .WriteString (w , "URL: " + r .URL .String ())
18
+ }
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "io"
5
+ "net/http"
6
+ "time"
7
+ )
8
+
9
+ var mux map [string ]func (http.ResponseWriter , * http.Request )
10
+
11
+ func main () {
12
+ server := http.Server {
13
+ Addr : ":8080" ,
14
+ Handler : & MyHandler {},
15
+ ReadTimeout : 6 * time .Second ,
16
+ }
17
+ mux = make (map [string ]func (http.ResponseWriter , * http.Request ))
18
+ mux ["/hello" ] = hello
19
+ mux ["/bye" ] = bye
20
+
21
+ server .ListenAndServe ()
22
+ }
23
+
24
+ type MyHandler struct {}
25
+
26
+ func (* MyHandler ) ServeHTTP (w http.ResponseWriter , r * http.Request ) {
27
+ if h , ok := mux [r .URL .String ()]; ok {
28
+ h (w , r )
29
+ }
30
+ io .WriteString (w , "\n URL: " + r .URL .String ())
31
+ }
32
+
33
+ func hello (w http.ResponseWriter , r * http.Request ) {
34
+ io .WriteString (w , "hello module" )
35
+ }
36
+
37
+ func bye (w http.ResponseWriter , r * http.Request ) {
38
+ io .WriteString (w , "bye module" )
39
+ }
You can’t perform that action at this time.
0 commit comments