diff --git a/obs/project.go b/obs/project.go index 1a57505..55a99fe 100644 --- a/obs/project.go +++ b/obs/project.go @@ -17,6 +17,7 @@ limitations under the License. package obs import ( + "bytes" "encoding/xml" "fmt" "net/http" @@ -112,6 +113,54 @@ func (e *APIError) Error() string { return fmt.Sprintf("HTTP status %d: %s (%s)", e.HTTPStatusCode, e.XMLStatusCode, e.Message) } +func (c Client) CreateProject(project *Project) error { + xmlData, err := xml.MarshalIndent(project, "", " ") + if err != nil { + return err + } + + urlPath := path.Join(c.APIURL, "source", project.Name, "_meta") + req, err := http.NewRequest("PUT", urlPath, bytes.NewBuffer(xmlData)) + if err != nil { + return &APIError{ + HTTPStatusCode: http.StatusInternalServerError, + XMLStatusCode: "", + Message: fmt.Sprintf("failed to generate a new request: %v", err), + } + } + + req.SetBasicAuth(c.Username, c.Password) + req.Header.Set("Accept", "application/xml; charset=utf-8") + + resp, err := c.Client.Do(req) + if err != nil { + return &APIError{ + HTTPStatusCode: resp.StatusCode, + XMLStatusCode: "", + Message: fmt.Sprintf("failed to make a new request: %v", err), + } + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + var status Status + if err := xml.NewDecoder(resp.Body).Decode(&status); err != nil { + return &APIError{ + HTTPStatusCode: resp.StatusCode, + XMLStatusCode: "", + Message: fmt.Sprintf("failed to decode the error response: %v", err), + } + } + + return &APIError{ + HTTPStatusCode: resp.StatusCode, + XMLStatusCode: status.Code, + Message: status.Summary, + } + } + return nil +} + func (c Client) DeleteProject(project *Project) error { urlPath := path.Join(c.APIURL, "source", project.Name) req, err := http.NewRequest("DELETE", urlPath, nil) @@ -134,6 +183,7 @@ func (c Client) DeleteProject(project *Project) error { Message: fmt.Sprintf("failed to make a new request: %v", err), } } + defer resp.Body.Close() if resp.StatusCode != http.StatusOK { var status Status @@ -151,6 +201,5 @@ func (c Client) DeleteProject(project *Project) error { Message: status.Summary, } } - return nil }