jlelse
/
hugo-micropub
Archived
1
Fork 0
This repository has been archived on 2020-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
hugo-micropub/gitea.go

56 lines
1.5 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
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
2019-12-06 09:32:30 +00:00
resp, err := http.Post(GiteaEndpoint+url.QueryEscape(path)+"?access_token="+GiteaToken, "application/json", bytes.NewBuffer(bytesRepresentation))
2019-11-07 10:00:24 +00:00
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) {
2019-12-06 09:32:30 +00:00
resp, err := http.Get(GiteaEndpoint + url.QueryEscape(path) + "?access_token=" + GiteaToken)
2019-11-14 17:46:49 +00:00
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
}