OSDN Git Service

add DeployHTLCContract
[bytom/shuttle.git] / swap / request.go
1 package swap
2
3 import (
4         "bytes"
5         "encoding/json"
6         "errors"
7         "io/ioutil"
8         "net/http"
9 )
10
11 var (
12         localURL = "http://127.0.0.1:9888/"
13
14         buildTransactionURL   = localURL + "build-transaction"
15         getTransactionURL     = localURL + "get-transaction"
16         signTransactionURL    = localURL + "sign-transaction"
17         submitTransactionURL  = localURL + "submit-transaction"
18         compileURL            = localURL + "compile"
19         decodeProgramURL      = localURL + "decode-program"
20         listAccountsURL       = localURL + "list-accounts"
21         listAddressesURL      = localURL + "list-addresses"
22         listBalancesURL       = localURL + "list-balances"
23         listPubkeysURL        = localURL + "list-pubkeys"
24         listUnspentOutputsURL = localURL + "list-unspent-outputs"
25 )
26
27 type response struct {
28         Status    string          `json:"status"`
29         Data      json.RawMessage `json:"data"`
30         ErrDetail string          `json:"error_detail"`
31 }
32
33 func request(url string, payload []byte, respData interface{}) error {
34         resp := &response{}
35         if err := post(url, payload, resp); err != nil {
36                 return err
37         }
38
39         if resp.Status != "success" {
40                 return errors.New(resp.ErrDetail)
41         }
42
43         return json.Unmarshal(resp.Data, respData)
44 }
45
46 func post(url string, payload []byte, result interface{}) error {
47         return PostWithHeader(url, nil, payload, result)
48 }
49
50 func PostWithHeader(url string, header map[string]string, payload []byte, result interface{}) error {
51         req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
52         if err != nil {
53                 return err
54         }
55
56         // set Content-Type in advance, and overwrite Content-Type if provided
57         req.Header.Set("Content-Type", "application/json")
58         for k, v := range header {
59                 req.Header.Set(k, v)
60         }
61
62         client := &http.Client{}
63         resp, err := client.Do(req)
64         if err != nil {
65                 return err
66         }
67
68         defer resp.Body.Close()
69         if result == nil {
70                 return nil
71         }
72
73         body, err := ioutil.ReadAll(resp.Body)
74         if err != nil {
75                 return err
76         }
77
78         return json.Unmarshal(body, result)
79 }