46 lines
783 B
Go
46 lines
783 B
Go
package new
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
d "github.com/karincake/dodol"
|
|
)
|
|
|
|
func DoJsonRequest(input any, method, endpoint string) error {
|
|
jsonData, err := json.Marshal(input)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to encode JSON: %w", err)
|
|
}
|
|
|
|
req, err := http.NewRequest(method, endpoint, bytes.NewReader(jsonData))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
bodyBytes, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
errors := d.FieldError{}
|
|
_ = json.Unmarshal(bodyBytes, &errors)
|
|
|
|
return fmt.Errorf(errors.Message)
|
|
}
|
|
|
|
return nil
|
|
}
|