Created
August 30, 2016 14:17
-
-
Save ianrose14/6b25bcce679b25ff20fe7463f75682ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"strings" | |
) | |
type StrBuf struct { | |
data []byte | |
off int | |
} | |
func (buf *StrBuf) Read(p []byte) (int, error) { | |
if buf.off >= len(buf.data) { | |
return 0, io.EOF | |
} | |
n := copy(p, buf.data[buf.off:]) | |
buf.off += n | |
if buf.off > len(buf.data) { | |
return 0, fmt.Errorf("over-read? len(buf.data) = %d, but buf.off = %d", len(buf.data), buf.off) | |
} | |
return n, nil | |
} | |
func main() { | |
body := `{"foo":5}` | |
client := http.Client{} | |
urlStr := "http://localhost:9999/foo" | |
var rdr io.Reader | |
// comment out one of the following lines | |
rdr = &StrBuf{data: []byte(body)} | |
rdr = strings.NewReader(body) | |
req, err := http.NewRequest("POST", urlStr, rdr) | |
if err != nil { | |
log.Fatalf("failed to make request: %s", err) | |
} | |
req.Header.Set("Content-Type", "application/json") | |
rsp, err := client.Do(req) | |
if err != nil { | |
log.Fatalf("failed to do post: %s", err) | |
} | |
log.Printf("done! status = %s", rsp.Status) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment