ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 实例 ~~~ import ( "fmt" "net/http" "strings" ) func myHandler(w http.ResponseWriter, r *http.Request) { //解析参数,默认是不会解析的 r.ParseForm() fmt.Fprintf(w, "%v\n", r.Form) fmt.Fprintf(w, "path:%s\n", r.URL.Path) fmt.Fprintf(w, "schema:%s\n", r.URL.Scheme) //get查询字符串 fmt.Fprintf(w, "form:%s\n", r.Form) //控制台打印 for k, v := range r.Form { fmt.Println("key: ", k) fmt.Println("value: ", strings.Join(v, "")) } fmt.Fprintf(w, "hello world\n") } func main() { //第一个参数是url的 http.HandleFunc("/health", myHandler) //用于指定的tcp网络地址监听 //第一个参数是监听地址,第二个参数是服务端处理程序,通常为空,为空表示服务端调用http.DefaultServeMux处理 err := http.ListenAndServe("127.0.0.1:8183", nil) if err != nil { fmt.Println("有错误: ", err) } } ~~~ # httptest ~~~ import ( "fmt" "net/http" "net/http/httptest" "testing" ) func TestMyHandler(t *testing.T) { //创建一个请求 req, err := http.NewRequest("GET", "/health", nil) if err != nil { t.Fatal(err) } // 我们创建一个 ResponseRecorder (which satisfies http.ResponseWriter)来记录响应 rr := httptest.NewRecorder() //直接使用myHandler,传入参数rr,req myHandler(rr, req) // 检测返回的状态码 if status := rr.Code; status != http.StatusOK { t.Errorf("返回的状态码是: %v", status) } // 检测返回的数据 fmt.Println(rr.Body.String()) } ~~~