Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created March 25, 2012 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/2198757 to your computer and use it in GitHub Desktop.
Save elazarl/2198757 to your computer and use it in GitHub Desktop.
A draft code to read a partial response from http server
package main
import ("bufio"
"fmt"
"io"
"net/http"
"net"
"strings")
type readFirstCloseSecond struct {
r io.Reader
c io.Closer
}
func (rfcs *readFirstCloseSecond) Read(b []byte) (int,error) {
return rfcs.r.Read(b)
}
func (rfcs *readFirstCloseSecond) Close() error {
return rfcs.c.Close()
}
func partialResp(u string) (*http.Response,error) {
req,err := http.NewRequest("GET",u,nil)
if err != nil {return nil,err}
host := req.Host
if ! strings.Contains(host,":") {
host += ":80"
}
c,err := net.Dial("tcp",host)
if err != nil {return nil,err}
// Doesn't support proxy! Use req.WriteProxy to the proxy connection
req.Write(c)
resp,err := http.ReadResponse(bufio.NewReader(c),req)
if err != nil {c.Close();return nil,err}
resp.Body = &readFirstCloseSecond{resp.Body,c}
return resp,err
}
func panicOnErr(err error) {
if err != nil {
panic(err.Error())
}
}
func main() {
u := "http://fuller.zen.co.uk/"+
"test/100MB_nonzero.bin"
resp,err := partialResp(u)
panicOnErr(err)
b := make([]byte,10)
nr,err := resp.Body.Read(b)
if nr != len(b) {
println("read too little")
} else {
fmt.Println(b)
}
panicOnErr(err)
resp.Body.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment