package wordpress import ( "bytes" "encoding/json" "federated.computer/wp-sync-slowtwitch/utilities" "io" "net/http" "strings" ) type CreateImage struct { Url string } type CreateImageResponse struct { Id int `json:"id"` Link string `json:"link"` Slug string `json:"slug"` } func (parameters *CreateImage) Execute(baseUrl, user, pass string) (CreateImageResponse, error) { resp, err := http.Get(parameters.Url) if err != nil { return CreateImageResponse{}, err } defer utilities.CloseBodyAndCheckError(resp.Body) body, err := io.ReadAll(resp.Body) if err != nil { return CreateImageResponse{}, err } request, err := http.NewRequest("POST", baseUrl+"wp-json/wp/v2/media", bytes.NewReader(body)) if err != nil { return CreateImageResponse{}, err } filename := GetFileName(parameters.Url) request.Header.Set("Content-Disposition", `attachment;filename="`+filename+`"`) request.SetBasicAuth(user, pass) rsp, err := http.DefaultClient.Do(request) if err != nil { return CreateImageResponse{}, err } result, err := io.ReadAll(rsp.Body) if err != nil { return CreateImageResponse{}, err } var data CreateImageResponse err = json.Unmarshal(result, &data) if err != nil { return CreateImageResponse{}, err } return data, nil } func GetFileName(url string) string { urlSlices := strings.Split(url, "/") length := len(urlSlices) var output string for i, s := range urlSlices { if i == length-1 { output = s } } return output }