7Days Gee Day1 添加部分注释

main
独孤伶俜 2023-02-04 19:00:36 +08:00
parent 44895b8fe9
commit 97774d1cd7
3 changed files with 29 additions and 10 deletions

View File

@ -1,25 +1,33 @@
package main
import (
"fmt"
"net/http"
)
type Engine struct{}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
path := r.URL.Path
switch path {
case "/":
fmt.Fprintf(w, "URL.Path = %q", r.URL.Path)
case "/hello":
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q", k, v)
}
_, _ = w.Write([]byte("Hello Go"))
case "/gee":
_, _ = w.Write([]byte("Gee!!!"))
default:
fmt.Fprintf(w, "404 NOT FOUND: %s", r.URL)
_, _ = w.Write([]byte("天啊, 404啦!!!!"))
}
}
func main() {
engine := new(Engine)
http.ListenAndServe(":8000", engine)
}
//// 自定义ServeMux
//func main() {
// mux := new(http.ServeMux)
// mux.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
// _, _ = writer.Write([]byte("Hello Go"))
// })
// _ = http.ListenAndServe(":8000", mux)
//}

View File

@ -2,6 +2,7 @@ package gee
import (
"fmt"
"log"
"net/http"
)
@ -18,12 +19,15 @@ func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 获取连接的请求方式和路径
key := r.Method + "-" + r.URL.Path
// 对比和匹配路由
if handler, ok := engine.router[key]; ok {
handler, ok := engine.router[key]
if ok {
handler(w, r)
} else {
w.WriteHeader(http.StatusNotFound)
_, _ = fmt.Fprintf(w, "404 NOT FOUND: %s", r.URL)
}
// 这里我们加上时间,容易理解
log.Println("请求方式:", r.Method, r.URL.Path, "对应:", key, "是否对应上:", ok)
}
// Run 启动服务
@ -36,6 +40,8 @@ func (engine *Engine) Run(addr string) (err error) {
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
key := method + "-" + pattern
engine.router[key] = handler
// 打印对应的 key
fmt.Println("请求方式:", method, pattern, " 对应: ", key)
}
// GET 添加GET路由规则

View File

@ -7,19 +7,24 @@ import (
)
func main() {
// 创建 Engine 实例
r := gee.New()
// 增加一个 GET 路由, path 为 /
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello World"))
})
// 增加一个 GET 路由, path 为 /hello
r.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
for k, v := range r.Header {
_, _ = fmt.Fprintf(w, "Header[%q] = %q", k, v)
}
})
// 增加一个 POST 路由, path 为 /login
r.POST("/login", func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "POST login")
})
err := r.Run(":9000")
// 创建服务端口的监听并开启 Http 服务
err := r.Run(":8000")
if err != nil {
return
}