Skip to content

Instantly share code, notes, and snippets.

@yinchunxiang
Last active September 24, 2023 08:04
Show Gist options
  • Save yinchunxiang/ef170ce11927a2f057a32870e2dd4cd2 to your computer and use it in GitHub Desktop.
Save yinchunxiang/ef170ce11927a2f057a32870e2dd4cd2 to your computer and use it in GitHub Desktop.
send chunked request by golang
package main
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"github.com/benburkert/http"
//"net/http"
//"encoding/binary"
"os"
)
const (
chunk1 = "First Chunk"
chunk2 = "Second Chunk"
)
func main() {
rd, wr := io.Pipe()
//u, _ := url.Parse("http://httpbin.org/post?show_env=1")
//u, _ := url.Parse("http://requestb.in/zox5gczo")
u, _ := url.Parse("https://httpbin.org/post")
req := &http.Request{
Method: "POST",
ProtoMajor: 1,
ProtoMinor: 1,
URL: u,
TransferEncoding: []string{"chunked"},
Body: rd,
Header: make(map[string][]string),
}
req.Header.Set("Content-Type", "audio/pcm;bit=16;rate=8000")
client := http.DefaultClient
go func() {
buf := make([]byte, 300)
f, _ := os.Open("./tq.pcm")
for {
n, _ := f.Read(buf)
if 0 == n {
break
}
wr.Write(buf)
}
wr.Close()
}()
resp, err := client.Do(req)
if nil != err {
fmt.Println("error =>", err.Error())
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if nil != err {
fmt.Println("error =>", err.Error())
} else {
fmt.Println(string(body))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment