如何将StarRocks Stream Load的curl -T命令转为Go代码?
将StarRocks Stream Load的curl命令转为Go实现
先搞懂curl -T的工作原理
curl的-T参数本质是把指定文件的原始内容作为PUT请求的请求体直接发送,不需要复杂的表单上传格式。StarRocks的Stream Load接口就是接收这种原始文本(比如CSV)请求体,所以你的核心思路是对的——把文件内容作为请求体传给PUT请求。
你的代码是否正确?
你的代码核心逻辑没问题,但缺少几个关键部分:
- 没有设置curl里的所有请求头(label、column_separator、columns、Expect这些)
- 没添加用户名密码的认证
- 如果文件很大,一次性读入内存会占用过多资源,更优的方式是直接用文件句柄作为io.Reader
完整的Go实现代码
方式1:小文件直接读入内存(适合小文件)
package main import ( "bytes" "encoding/base64" "io" "net/http" "os" ) func main() { // 读取文件内容 filePath := "example1.csv" fileContents, err := os.ReadFile(filePath) if err != nil { panic(err) } // 替换为你的FE地址和端口 url := "http://<fe_host>:<fe_http_port>/api/mydatabase/table1/_stream_load" // 创建PUT请求,用文件内容作为请求体 req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(fileContents)) if err != nil { panic(err) } // 设置curl中定义的请求头 req.Header.Set("label", "123") req.Header.Set("Expect", "100-continue") req.Header.Set("column_separator", ",") req.Header.Set("columns", "id, name, score") // 添加用户名密码认证(对应curl的-u参数) username := "<username>" password := "<password>" authStr := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) req.Header.Set("Authorization", "Basic "+authStr) // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() // 读取并打印响应结果 respBody, err := io.ReadAll(resp.Body) if err != nil { panic(err) } println(string(respBody)) }
方式2:大文件流式上传(避免内存占用过高)
如果你的CSV文件体积较大,不要一次性读入内存,直接打开文件作为请求体流式上传:
package main import ( "encoding/base64" "io" "net/http" "os" ) func main() { // 打开文件,直接作为请求体 filePath := "example1.csv" file, err := os.Open(filePath) if err != nil { panic(err) } defer file.Close() // 替换为你的FE地址和端口 url := "http://<fe_host>:<fe_http_port>/api/mydatabase/table1/_stream_load" // 创建PUT请求,传入文件句柄作为io.Reader req, err := http.NewRequest(http.MethodPut, url, file) if err != nil { panic(err) } // 设置请求头和认证,和小文件方式一致 req.Header.Set("label", "123") req.Header.Set("Expect", "100-continue") req.Header.Set("column_separator", ",") req.Header.Set("columns", "id, name, score") username := "<username>" password := "<password>" authStr := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) req.Header.Set("Authorization", "Basic "+authStr) // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() respBody, err := io.ReadAll(resp.Body) if err != nil { panic(err) } println(string(respBody)) }
注意事项
- 替换代码中的
<fe_host>、<fe_http_port>、<username>、<password>为你的实际信息 Expect:100-continue头会让服务器先返回100响应确认接收,再发送文件内容,适合大文件上传场景- StarRocks的Stream Load会返回JSON格式的响应,你可以解析这个响应判断上传是否成功
内容的提问来源于stack exchange,提问作者Mikhail Andrianov
相关产品推荐
相关产品推荐

