ms-tester/pkg/external/pandoc/client.go
Vyacheslav1557 be25404852 feat:
2024-10-13 19:01:36 +05:00

72 lines
1.3 KiB
Go

package pandoc
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
)
type Client struct {
client *http.Client
address string
}
type PandocClient interface {
ConvertLatexToHtml5(ctx context.Context, text string) (string, error)
}
func NewPandocClient(client *http.Client, address string) *Client {
return &Client{
client: client,
address: address,
}
}
type convertRequest struct {
Text string `json:"text"`
From string `json:"from"`
To string `json:"to"`
}
func (client *Client) convert(ctx context.Context, text, from, to string) (string, error) {
body, err := json.Marshal(convertRequest{
Text: text,
From: from,
To: to,
})
if err != nil {
return "", err
}
buf := bytes.NewBuffer(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, client.address, buf)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", err
}
body, err = io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func (client *Client) ConvertLatexToHtml5(ctx context.Context, text string) (string, error) {
return client.convert(ctx, text, "latex", "html5")
}