2024-10-09 18:55:16 +00:00
|
|
|
package pandoc
|
2024-08-18 00:07:31 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2024-08-18 15:36:26 +00:00
|
|
|
"context"
|
2024-08-18 00:07:31 +00:00
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2024-10-09 18:55:16 +00:00
|
|
|
type Client struct {
|
2024-08-18 00:07:31 +00:00
|
|
|
client *http.Client
|
|
|
|
address string
|
|
|
|
}
|
|
|
|
|
2024-10-09 18:55:16 +00:00
|
|
|
type PandocClient interface {
|
|
|
|
ConvertLatexToHtml5(ctx context.Context, text string) (string, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPandocClient(client *http.Client, address string) *Client {
|
|
|
|
return &Client{
|
2024-08-18 00:07:31 +00:00
|
|
|
client: client,
|
|
|
|
address: address,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type convertRequest struct {
|
|
|
|
Text string `json:"text"`
|
|
|
|
From string `json:"from"`
|
|
|
|
To string `json:"to"`
|
|
|
|
}
|
|
|
|
|
2024-10-09 18:55:16 +00:00
|
|
|
func (client *Client) convert(ctx context.Context, text, from, to string) (string, error) {
|
2024-08-18 00:07:31 +00:00
|
|
|
body, err := json.Marshal(convertRequest{
|
|
|
|
Text: text,
|
|
|
|
From: from,
|
|
|
|
To: to,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := bytes.NewBuffer(body)
|
|
|
|
|
2024-08-18 15:36:26 +00:00
|
|
|
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)
|
2024-08-18 00:07:31 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-10-09 18:55:16 +00:00
|
|
|
func (client *Client) ConvertLatexToHtml5(ctx context.Context, text string) (string, error) {
|
2024-08-18 15:36:26 +00:00
|
|
|
return client.convert(ctx, text, "latex", "html5")
|
2024-08-18 00:07:31 +00:00
|
|
|
}
|