Files
mstore/pkg/accntcli/service.go
T
2026-03-07 19:11:20 +02:00

94 lines
2.2 KiB
Go

/*
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
*
* This work is published and licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* Distribution of this work is permitted, but commercial use and
* modifications are strictly prohibited.
*/
package accntcli
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"mstore/app/handler"
"mstore/app/imageoper"
)
func (cli *Client) ServiceHello(ctx context.Context, host string) (bool, error) {
var res bool
var err error
params := imageoper.SendHelloParams{}
reqdata, err := json.Marshal(params)
if err != nil {
return res, err
}
resdata, err := cli.doHTTPCall(ctx, host, "service", "hello", reqdata)
if err != nil {
return res, err
}
response := handler.Response[imageoper.SendHelloResult]{}
err = json.Unmarshal(resdata, &response)
if err != nil {
return res, err
}
if response.Error {
err = errors.New(response.Message)
return res, err
}
res = response.Result.Alive
return res, err
}
func (cli *Client) doHTTPCall(ctx context.Context, host, obj, oper string, req []byte) ([]byte, error) {
var err error
var res []byte
reader := bytes.NewReader(req)
ref, err := NewReferer(host, obj, oper)
if err != nil {
return res, err
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, ref.Point(), reader)
if err != nil {
return res, err
}
httpReq.Header.Set("User-Agent", cli.userAgent)
httpReq.Header.Set("Accept", "*/*")
httpResp, err := cli.httpClient.Do(httpReq)
if err != nil {
return res, err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
err := fmt.Errorf("Unexpected response code: %s", httpResp.Status)
return res, err
}
contentLength := httpResp.Header.Get("Content-Length")
if contentLength == "" {
err := fmt.Errorf("Content-Length header is missing")
return res, err
}
blobSize, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
return res, err
}
buffer := bytes.NewBuffer(nil)
recSize, err := io.Copy(buffer, httpResp.Body)
if blobSize != recSize {
err := fmt.Errorf("Mismatch declared and actual body size, %d and %d", blobSize, recSize)
return res, err
}
res = buffer.Bytes()
return res, err
}