Last active
April 22, 2021 13:27
-
-
Save wliao008/c23f1cebde8b946092c61cea3caf5bd9 to your computer and use it in GitHub Desktop.
upload package to aem server in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Packages can be uploaded via CURL as specified in this document: | |
https://experienceleague.adobe.com/docs/experience-manager-65/administering/operations/curl.html?lang=en#user-management | |
$ curl -u <user>:<password> -F cmd=upload -F force=true -F [email protected] http://localhost:4502/crx/packmgr/service/.json | |
This is how it can be done in Golang, please note I've removed all error checking for brevity. | |
*/ | |
import ( | |
"bytes" | |
"encoding/base64" | |
"encoding/json" | |
"errors" | |
"io/ioutil" | |
"mime/multipart" | |
"net/http" | |
"net/url" | |
"os" | |
"path" | |
) | |
type AemServer struct{} | |
type aemResp struct { | |
Success bool `json:"success"` | |
Msg string `json:"msg"` | |
Path string `json:"path"` | |
} | |
func (srv *AemServer) UploadPackage(server, pkg, username, password string) (*string, error) { | |
auth := username + ":" + password | |
b64 := base64.StdEncoding.EncodeToString([]byte(auth)) | |
u, _ := url.Parse(server) | |
u.Path = path.Join(u.Path, "crx/packmgr/service/.json") | |
file, _ := os.Open(pkg) //open the package (.zip) file | |
fileContents, _ := ioutil.ReadAll(file) | |
fi, _ := file.Stat() | |
defer file.Close() | |
body := new(bytes.Buffer) | |
writer := multipart.NewWriter(body) | |
part, _ := writer.CreateFormFile("package", fi.Name()) | |
part.Write(fileContents) | |
_ = writer.WriteField("cmd", "upload") | |
_ = writer.WriteField("force", "true") | |
_ = writer.Close() | |
req, _ := http.NewRequest("POST", u.String(), body) | |
req.Header.Add("Authorization", "Basic "+b64) | |
req.Header.Set("Content-Type", writer.FormDataContentType()) | |
client := &http.Client{} | |
resp, _ := client.Do(req) | |
bodyBytes, _ := ioutil.ReadAll(resp.Body) | |
var aemr aemResp | |
_ = json.Unmarshal(bodyBytes, &aemr) | |
if !aemr.Success { | |
return nil, errors.New(aemr.Msg) | |
} | |
return &aemr.Path, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment