hugo-micropub/gitea.go

72 lines
1.7 KiB
Go
Raw Normal View History

2019-11-07 10:00:24 +00:00
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
2019-11-14 17:46:49 +00:00
"io/ioutil"
2019-11-07 10:00:24 +00:00
"net/http"
"net/url"
)
2019-11-14 17:46:49 +00:00
func CreateFile(path string, file string, name string) error {
2019-11-07 10:00:24 +00:00
giteaEndpoint, err := GetGiteaEndpoint()
if err != nil {
return err
}
giteaToken, err := GetGiteaToken()
if err != nil {
return err
}
message := map[string]interface{}{
"message": name,
"content": base64.StdEncoding.EncodeToString([]byte(file)),
}
bytesRepresentation, err := json.Marshal(message)
if err != nil {
return errors.New("failed to marshal json before committing")
}
// TODO: handle file updating
resp, err := http.Post(giteaEndpoint+url.QueryEscape(path)+"?access_token="+giteaToken, "application/json", bytes.NewBuffer(bytesRepresentation))
if err != nil || resp.StatusCode != 201 {
return errors.New("failed to create file in repo")
}
return nil
}
2019-11-14 17:46:49 +00:00
func ReadFile(path string) (fileContent string, err error) {
giteaEndpoint, err := GetGiteaEndpoint()
if err != nil {
return
}
giteaToken, err := GetGiteaToken()
if err != nil {
return
}
resp, err := http.Get(giteaEndpoint + url.QueryEscape(path) + "?access_token=" + giteaToken)
if err != nil || resp.StatusCode != 200 {
err = errors.New("failed to read file in repo")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
err = errors.New("failed reading file in repo")
return
}
giteaResponseBody := struct {
Content string
}{}
err = json.Unmarshal(body, &giteaResponseBody)
if err != nil {
err = errors.New("failed parsing Gitea response")
return
}
decodedBytes, err := base64.StdEncoding.DecodeString(giteaResponseBody.Content)
if err != nil {
err = errors.New("failed decoding file content")
}
fileContent = string(decodedBytes)
return
}