62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
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)
|
||
}
|