add: web基本知识

This commit is contained in:
xiaowei 2022-02-13 10:34:46 +08:00
parent acadb8457f
commit 500c147acb
2 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,26 @@
package main
import (
"fmt"
"net/http"
)
func main() {
// 路由1
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello basic web!")
})
// 路由2
http.HandleFunc("/xiaowei", func(w http.ResponseWriter, r *http.Request) {
headers := r.Header
for k, v := range headers {
fmt.Fprintf(w, "[%v]-[%v]\n", k, v)
}
})
// 启动一个httpserver
if err := http.ListenAndServe(":9000", nil); err != nil {
panic(err)
}
}

View File

@ -0,0 +1,29 @@
package main
import (
"fmt"
"net/http"
)
// Engine 定义一个结构体
type Engine struct {
}
// 实现Handler的ServerHTTP方法
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.RequestURI {
case "/":
fmt.Fprint(w, "hello handler-basic")
case "/web":
for k, v := range r.Header {
fmt.Fprintln(w, k, "-->", v)
}
}
}
func main() {
engine := new(Engine)
if err := http.ListenAndServe(":9000", engine); err != nil {
panic(err)
}
}