Пример #1
0
func init() {
	c.Replace(test.New().Handle(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		ctn := Content{
			Method:        r.Method,
			Path:          strings.TrimLeft(r.URL.Path, "/"),
			ContentType:   r.Header.Get("Content-Type"),
			ContentLength: r.ContentLength,
		}

		err := r.ParseForm()
		if err != nil {
			ctn.FormData = err.Error()
		} else {
			switch r.Method {
			// https://golang.org/src/net/http/request.go?s=28722:28757#L924
			// NOTE: ACC DELETE Method 需要將 payload 放置 body, 但是 golang http.Request.ParseForm 僅處理 PUT/POST/PATCH 內的 body
			case "DELETE":
				if b, e := ioutil.ReadAll(r.Body); e == nil {
					ctn.FormData = string(b)
				} else {
					ctn.FormData = e.Error()
				}
			default:
				ctn.FormData = r.Form.Encode()
			}
		}

		if b, err := json.Marshal(ctn); err == nil {
			w.Write(b)
		} else {
			w.Write([]byte(err.Error()))
		}
	}))
}
Пример #2
0
func ExampleHttpError() {

	c := New("http://127.0.0.1:8000")
	c.Replace(test.New().Handle(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "test error code", 404)
	}))

	ctn, status, err := c.Get("error/404", nil)
	fmt.Println(err)
	fmt.Println(status)
	fmt.Println(string(ctn))
	// Output:
	// http error [404]
	// 404
	// test error code
}