Skip to content

Instantly share code, notes, and snippets.

@redbo
Created July 1, 2015 23:48
Show Gist options
  • Save redbo/26200053d2f593d7ca98 to your computer and use it in GitHub Desktop.
Save redbo/26200053d2f593d7ca98 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
)
func DoRequest(req *http.Request, c net.Conn) (*http.Response, error) {
defer req.Body.Close()
dumped, err := httputil.DumpRequestOut(req, false)
if err != nil {
return nil, err
}
if _, err = c.Write(dumped); err != nil {
return nil, err
}
reader := bufio.NewReader(c)
resp, err := http.ReadResponse(reader, req)
if err != nil {
return nil, err
}
if resp.StatusCode == 100 {
io.Copy(c, req.Body)
resp, err = http.ReadResponse(reader, req)
}
return resp, nil
}
var bodySize = 25
type FakeReader struct {
readFrom bool
}
func (f *FakeReader) Read(p []byte) (int, error) {
if !f.readFrom {
f.readFrom = true
return 25, nil
}
return 0, io.EOF
}
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/readbody" {
data, err := ioutil.ReadAll(r.Body)
if err != nil || len(data) != 25 {
fmt.Println("Error reading body from request.")
}
}
w.WriteHeader(200)
}))
c, err := net.Dial("tcp", server.Listener.Addr().String())
if err != nil {
fmt.Println("Error connecting to server", err)
return
}
body := &FakeReader{readFrom: false}
req, _ := http.NewRequest("POST", server.URL+"/readbody", body)
req.Header.Add("Expect", "100-Continue")
req.Header.Add("Content-Length", "25")
req.ContentLength = 25
resp, err := DoRequest(req, c)
if err != nil {
fmt.Println("Request error", err)
return
}
if !body.readFrom {
fmt.Println("Body should have been read, but wasn't.")
}
fmt.Println("Response status:", resp.StatusCode)
body = &FakeReader{readFrom: false}
req, _ = http.NewRequest("POST", server.URL+"/dontreadbody", body)
req.Header.Add("Expect", "100-Continue")
req.ContentLength = int64(bodySize)
resp, err = DoRequest(req, c)
if err != nil {
fmt.Println("Request error", err)
return
}
if body.readFrom {
fmt.Println("Body shouldn't have been read, but was.")
}
fmt.Println("Response status:", resp.StatusCode)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment