72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
func CreateFile(path string, file string, name string) error {
|
|
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
|
|
}
|
|
|
|
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
|
|
} |