Matrix/request.go

72 lines
1.4 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"mime/multipart"
"github.com/go-resty/resty/v2"
)
func createInsructions(marshal []byte) (*bytes.Buffer, string) {
// Create a new form data object
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add the "instructions" key with the value of marshal
part, err := writer.CreateFormField("instructions")
if err != nil {
log.Fatal(err)
return nil, ""
}
part.Write(marshal)
// Close the multipart writer
writer.Close()
return body, writer.FormDataContentType()
}
func sendRequest(client *resty.Client, url string, ins []interface{}) {
// Manually marshal instructions
marshal, err := json.Marshal(ins)
if err != nil {
log.Fatal(err)
return
}
// Create instructions form data
req, content := createInsructions(marshal)
if req == nil {
return
}
// Build and send request
res, err := client.R().
SetHeader("Content-Type", content).
SetBody(req.Bytes()).
Post(fmt.Sprintf("%s/instructions", url))
// Error handling
if err != nil {
log.Fatal(err)
return
}
// Unmarshal response
var data Response
err = json.Unmarshal(res.Body(), &data)
if err != nil {
log.Fatal(err)
return
}
// Print response
if !data.Success {
log.Fatal(errors.New("Remote server responded unsuccessfully!"))
}
}