50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package gemlog
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
func SaveGemlogEntry(config *Config, entry *GemlogEntry) error {
|
|
url := fmt.Sprintf("%s:%d/gemlog/", config.CouchDB.Host, config.CouchDB.Port)
|
|
|
|
// Marshal the entry struct to JSON
|
|
jsonData, err := json.Marshal(entry)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal entry: %w", err)
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create request: %w", err)
|
|
}
|
|
|
|
// Encode username:password for Basic Auth
|
|
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", config.CouchDB.User, config.CouchDB.Password)))
|
|
req.Header.Add("authorization", fmt.Sprintf("Basic %s", auth))
|
|
req.Header.Add("content-type", "application/json")
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to send request: %w", err)
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read response body: %w", err)
|
|
}
|
|
|
|
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
|
return fmt.Errorf("unexpected status code %d: %s", res.StatusCode, string(body))
|
|
}
|
|
|
|
// fmt.Println(res)
|
|
// fmt.Println(string(body))
|
|
|
|
return nil
|
|
}
|