course/HTTP/http_server.go

40 lines
769 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"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)
}
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)
http.HandleFunc("/query", f2)
http.ListenAndServe("127.0.0.1:9090", nil)
}