From 85b96a5ea352088d5480b15af13ccab2a195ea75 Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Fri, 12 Apr 2024 11:58:13 +0200 Subject: [PATCH] write marshaled string into form data --- main.go | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 6370141..231338e 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,12 @@ package main import ( + "bytes" "encoding/json" "errors" "fmt" "log" + "mime/multipart" "os" "strconv" @@ -116,6 +118,25 @@ func LoadMatrixData() (string, int, int) { return url, width, height } +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) @@ -127,10 +148,16 @@ func SendRequest(client *resty.Client, url string, ins []interface{}) { // Debug log json data log.Printf("Request: %s\n", string(marshal)) + // Create instructions form data + req, content := CreateInsructions(marshal) + if req == nil { + return + } + // Build and send request - resp, err := client.R(). - SetHeader("Content-Type", "application/json"). - SetBody(ins). + res, err := client.R(). + SetHeader("Content-Type", content). + SetBody(req.Bytes()). Post(fmt.Sprintf("%s/instructions", url)) // Error handling @@ -140,11 +167,11 @@ func SendRequest(client *resty.Client, url string, ins []interface{}) { } // Print response status - log.Printf("Response Status: %s\n", resp.Status()) + log.Printf("Response Status: %s\n", res.Status()) // Unmarshal response var data Response - err = json.Unmarshal(resp.Body(), &data) + err = json.Unmarshal(res.Body(), &data) if err != nil { log.Fatal(err) return