Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9ec9ed3

Browse files
committed
http package
1 parent a984a56 commit 9ec9ed3

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

‎http/Step1/web.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
// }

‎http/Step2/web.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}

‎http/Step3/web.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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, "\nURL: "+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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /