This repository has been archived by the owner on Jul 2, 2024. It is now read-only.
forked from datacontract/datacontract-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
open.go
91 lines (71 loc) · 2.13 KB
/
open.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package datacontract
import (
"fmt"
"github.com/pkg/browser"
"log"
"net/http"
"net/url"
"os"
"strings"
)
func Open(dataContractFileName string, dataContractStudioUrl string) error {
contractUrl, err := createDataContractInStudio(dataContractFileName, dataContractStudioUrl)
if err != nil {
return err
}
err = openDataContractInBrowser(contractUrl)
if err != nil {
return err
}
return nil
}
func createDataContractInStudio(dataContractFileName string, dataContractStudioUrl string) (string, error) {
file, err := os.ReadFile(dataContractFileName)
if err != nil {
return "", err
}
id, err := newDataContract(dataContractStudioUrl)
if err != nil {
return "", err
}
contractUrl, err := sendDataContract(dataContractStudioUrl, id, file)
if err != nil {
return "", err
}
return contractUrl, nil
}
func newDataContract(dataContractStudioUrl string) (string, error) {
r, err := postForm(dataContractStudioUrl+"/new", nil)
if err != nil {
return "", fmt.Errorf("failed to create new data contract id: %w", err)
}
strings := strings.Split(r.Request.URL.Path, "/")
if len(strings) < 2 {
return "", fmt.Errorf("cant extract data contract id from %v", r.Request.URL.Path)
}
return strings[len(strings)-2], nil
}
func sendDataContract(dataContractStudioUrl string, id string, file []byte) (string, error) {
contractUrl := dataContractStudioUrl + "/" + id
_, err := postForm(contractUrl+"/save", url.Values{"yaml": {string(file)}})
if err != nil {
return "", fmt.Errorf("failed to send data contract: %w", err)
}
return contractUrl, nil
}
func openDataContractInBrowser(contractUrl string) error {
log.Println("🌐 opening data contract at " + contractUrl)
err := browser.OpenURL(contractUrl)
return err
}
func postForm(formUrl string, formData url.Values) (*http.Response, error) {
response, err := http.PostForm(formUrl, formData)
if err != nil {
return nil, fmt.Errorf("form post to %v failed: %w", formUrl, err)
}
defer response.Body.Close()
if !(response.StatusCode >= 200 && response.StatusCode < 300) {
return nil, fmt.Errorf("form post to %v failed: %v", formUrl, response.Status)
}
return response, nil
}