Files
ginimageApi/app/mcp/http_helpers.go
Beyhan Oğur e04ba85564 first commit
2026-04-26 21:40:14 +03:00

62 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package mcp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
// doAPIRequest genel amaçlı HTTP istek yardımcısı
func doAPIRequest(ctx context.Context, method, path, bearer string, body interface{}) (int, string, error) {
baseURL := resolveBaseURLFromContext(ctx)
url := strings.TrimRight(baseURL, "/") + ensurePathPrefix(path)
var bodyReader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return 0, "", fmt.Errorf("request body marshal error: %v", err)
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return 0, "", fmt.Errorf("request creation error: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return 0, "", fmt.Errorf("request error: %v", err)
}
defer resp.Body.Close()
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, "", fmt.Errorf("response read error: %v", err)
}
// Pretty-print JSON yanıt
var prettyBuf bytes.Buffer
if json.Indent(&prettyBuf, respBytes, "", " ") == nil {
return resp.StatusCode, prettyBuf.String(), nil
}
return resp.StatusCode, string(respBytes), nil
}
// apiResult tool sonucu formatlar
func apiResult(status int, body string) string {
return fmt.Sprintf("HTTP %d\n%s", status, body)
}