1 回答
TA贡献1836条经验 获得超13个赞
解决方案:
func createForm(form map[string]string) (string, io.Reader, error) {
body := new(bytes.Buffer)
mp := multipart.NewWriter(body)
defer func(mp *multipart.Writer) {
err := mp.Close()
if err != nil {
}
}(mp)
var file *os.File
for key, val := range form {
if strings.HasPrefix(val, "@") {
val = val[1:]
file, err := os.Open(val)
if err != nil {
return "", nil, err
}
part, err := mp.CreateFormFile(key, val)
if err != nil {
return "", nil, err
}
_, err = io.Copy(part, file)
if err != nil {
return "", nil, err
}
} else {
err := mp.WriteField(key, val)
if err != nil {
return "", nil, err
}
}
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
}
}(file)
return mp.FormDataContentType(), body, nil
}
func AttachFileToIssue(path string, issueID string) string {
form := map[string]string{"path": "@" + path}
mp, body, err := createForm(form)
if err != nil {
panic(err)
}
req, err := http.NewRequest("POST", youTrackUrl+"/api/issues/"+issueID+"/attachments?fields=id,name", body)
if err != nil {
// handle err
}
req.Header.Set("Authorization", "Bearer "+youTrackToken)
req.Header.Set("Content-Type", mp)
resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
}
if resp.StatusCode == http.StatusOK {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
return bodyString
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
return ""
}
- 1 回答
- 0 关注
- 131 浏览
添加回答
举报