|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "github.com/spf13/viper" |
| 8 | + "io" |
| 9 | + "mime/multipart" |
| 10 | + "net/http" |
| 11 | + "net/url" |
| 12 | + "os" |
| 13 | + "path/filepath" |
| 14 | + |
| 15 | + "github.com/kondukto-io/kdt/klog" |
| 16 | +) |
| 17 | + |
| 18 | +func (c *Client) ImportEndpoint(filePath string, projectName string) error { |
| 19 | + klog.Debugf("importing endpoint using file:%s", filePath) |
| 20 | + |
| 21 | + if filePath == "" { |
| 22 | + return errors.New("file parameter is required") |
| 23 | + } |
| 24 | + |
| 25 | + projectDoc, err := c.FindProjectByName(projectName) |
| 26 | + if err != nil || projectDoc == nil { |
| 27 | + return fmt.Errorf("no projects found for name [%s]", projectName) |
| 28 | + } |
| 29 | + |
| 30 | + if _, err := os.Stat(filePath); os.IsNotExist(err) { |
| 31 | + return fmt.Errorf("file does not exist: %s", filePath) |
| 32 | + } |
| 33 | + |
| 34 | + path := fmt.Sprintf("/api/v2/projects/%s/apispecs", projectDoc.ID) |
| 35 | + rel := &url.URL{Path: path} |
| 36 | + u := c.BaseURL.ResolveReference(rel) |
| 37 | + |
| 38 | + body := &bytes.Buffer{} |
| 39 | + writer := multipart.NewWriter(body) |
| 40 | + |
| 41 | + file, err := os.Open(filePath) |
| 42 | + if err != nil { |
| 43 | + return fmt.Errorf("failed to open file: %w", err) |
| 44 | + } |
| 45 | + defer file.Close() |
| 46 | + |
| 47 | + part, err := writer.CreateFormFile("file", filepath.Base(filePath)) |
| 48 | + if err != nil { |
| 49 | + return fmt.Errorf("failed to create form file: %w", err) |
| 50 | + } |
| 51 | + |
| 52 | + if _, err = io.Copy(part, file); err != nil { |
| 53 | + return fmt.Errorf("failed to copy file content: %w", err) |
| 54 | + } |
| 55 | + |
| 56 | + if err = writer.Close(); err != nil { |
| 57 | + return fmt.Errorf("failed to close writer: %w", err) |
| 58 | + } |
| 59 | + |
| 60 | + req, err := http.NewRequest(http.MethodPost, u.String(), body) |
| 61 | + if err != nil { |
| 62 | + return fmt.Errorf("failed to create request: %w", err) |
| 63 | + } |
| 64 | + |
| 65 | + req.Header.Set("Content-Type", writer.FormDataContentType()) |
| 66 | + req.Header.Set("Accept", "application/json") |
| 67 | + req.Header.Set("User-Agent", userAgent) |
| 68 | + req.Header.Set("X-Cookie", viper.GetString("token")) |
| 69 | + |
| 70 | + resp, err := c.do(req, nil) |
| 71 | + if err != nil { |
| 72 | + return fmt.Errorf("request failed: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + if resp.StatusCode != http.StatusOK { |
| 76 | + return fmt.Errorf("failed to import endpoint: %s", resp.Status) |
| 77 | + } |
| 78 | + |
| 79 | + return nil |
| 80 | +} |
0 commit comments