-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
100 lines (85 loc) · 1.95 KB
/
init.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
92
93
94
95
96
97
98
99
100
package filemgr
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/ufilesdk-dev/ufile-gosdk"
"io/ioutil"
"net/http"
"strings"
)
type Client struct {
Namespace string
Key string
Region string
FileHost string
Conf *ufsdk.Config
}
func NewClient(namespace, key, fileHost string, regions ...string) (*Client, error) {
region := "default"
if len(regions) != 0 {
region = regions[0]
}
if !strings.HasSuffix(fileHost, "/") {
fileHost = fileHost + "/"
}
c := &Client{
Namespace:namespace,
Key:key,
FileHost:fileHost,
Region:region,
}
err := c.check()
if err != nil {
fmt.Println("namespace check error. ", err.Error())
return nil, err
}
return c, nil
}
func (c *Client) check() error {
// jc, err := LoadConf(configFile)
bodyJson, err := json.Marshal(struct {
Namespace string `json:"namespace"`
Key string `json:"key"`
Region string `json:"region"`
}{
Namespace: c.Namespace,
Key:c.Key,
Region: c.Region,
})
if err != nil {
fmt.Println("json marshal error. ", err.Error())
return err
}
res, err := http.Post(c.FileHost + "check", "application/json", bytes.NewBuffer(bodyJson))
if err != nil {
fmt.Printf("send request error. url: %s. err: %s\n", c.FileHost, err)
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("parse body error. ", err)
return err
}
mp := make(map[string]interface{})
err = json.Unmarshal(body, &mp)
if err != nil {
fmt.Println("json unmarshal error. ", err.Error())
return err
}
cf := new(ufsdk.Config)
if res.StatusCode != 200 {
return errors.Errorf("%s",mp["data"])
} else {
tmp := mp["data"].(map[string]interface{})
cf.FileHost = fmt.Sprint(tmp["FileHost"])
cf.PublicKey = fmt.Sprint(tmp["PublicKey"])
cf.PrivateKey = fmt.Sprint(tmp["PrivateKey"])
cf.BucketName = fmt.Sprint(tmp["BucketName"])
cf.BucketHost = fmt.Sprint(tmp["BucketHost"])
}
c.Conf = cf
return nil
}