course/HTTP/http_server.go

40 lines
769 B
Go
Raw Normal View History

package main
import (
"fmt"
2024-07-14 11:08:04 +08:00
"io"
"net/http"
"os"
)
func f1(w http.ResponseWriter, r *http.Request) {
b, err := os.ReadFile("./HTTP/fronted.html")
if err != nil {
w.Write([]byte(fmt.Sprintf("%v", err)))
return
}
w.Write(b)
}
2024-07-14 11:08:04 +08:00
func f2(w http.ResponseWriter, r *http.Request) {
//对于GET请求query param参数都放在url请求体中没有数据
queryParam := r.URL.Query()
name := queryParam.Get("name")
age := queryParam.Get("age")
fmt.Println(name, age) //自动识别url中的问号中的参数
fmt.Println(r.URL)
fmt.Println(r.Method)
fmt.Println(io.ReadAll(r.Body))
w.Write([]byte("success"))
}
// http server
func main() {
http.HandleFunc("/web", f1)
2024-07-14 11:08:04 +08:00
http.HandleFunc("/query", f2)
http.ListenAndServe("127.0.0.1:9090", nil)
}