oc-deploy/publish/releases/assets.go
2024-09-13 12:43:09 +00:00

146 lines
3.3 KiB
Go

package releases
import (
"fmt"
"os"
"path/filepath"
"mime/multipart"
"io"
"io/ioutil"
"encoding/json"
"net/http"
"bytes"
"oc-publish/occonst"
)
type assetStruct struct {
Name string `json:"name"`
Id int `json:"id"`
}
func GetAssetId(idRelease int, name string) (int, error) {
url := fmt.Sprintf("%s/api/v1/repos/%s/releases/%d/assets",
occonst.PUBLISH_URL,
occonst.PUBLISH_REPO,
idRelease)
res, err := http.Get(url)
if err != nil {
return -1, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return -2, err
}
var data []assetStruct
err = json.Unmarshal(body, &data)
if err != nil {
return -3, err
}
for _, ele := range data {
if ele.Name == name {
return ele.Id, nil
}
}
return 0, nil
}
// curl -X 'POST' \
// 'https://cloud.o-forge.io/api/v1/repos/core/oc-deploy/releases/2/assets?name=zzzz' \
// -H 'accept: application/json' \
// -H 'Content-Type: multipart/form-data' \
// -F 'attachment=oc-deploy'
func CreateAsset(idRelease int, filename string, name string) (error) {
url := fmt.Sprintf("%s/api/v1/repos/%s/releases/%d/assets?name=%s&token=%s",
occonst.PUBLISH_URL,
occonst.PUBLISH_REPO,
idRelease,
name,
occonst.PUBLISH_TOKEN)
err := uploadFile(url, "attachment", filename)
return err
}
func UpdateAsset(idRelease int, idAsset int, filename string, name string) (error) {
url := fmt.Sprintf("%s/api/v1/repos/%s/releases/%d/assets/%d?token=%s",
occonst.PUBLISH_URL,
occonst.PUBLISH_REPO,
idRelease,
idAsset,
occonst.PUBLISH_TOKEN)
// Create client
client := &http.Client{}
// Create request
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
// Fetch Request
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Read Response Body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(string(respBody))
return CreateAsset(idRelease, filename, name)
}
func uploadFile(url string, paramName string, filePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(filePath))
if err != nil {
return err
}
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return err
}
request, err := http.NewRequest("POST", url, body)
request.Header.Add("Content-Type", writer.FormDataContentType())
request.Header.Add("accept", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println(109, err)
return err
}
defer response.Body.Close()
if response.StatusCode > 400 {
return fmt.Errorf(response.Status)
}
_, err1 := io.ReadAll(response.Body)
// Handle the server response...
return err1
}