package btc import ( "bytes" "encoding/json" "fmt" "io" "log" "net/http" ) const ( GET_BLOCK RPCMethod = "getblock" GET_BALANCE RPCMethod = "getbalance" GET_RAW_TRANSACTION RPCMethod = "getrawtransaction" GET_TRANSACTION RPCMethod = "gettransaction" DECODE_RAW_TRANSACTION RPCMethod = "decoderawtransaction" LIST_ADDRESS_GROUPINGS RPCMethod = "listaddressgroupings" ) type RPCMethod string type RPCRequest struct { host string auth string Jsonrpc string `json:"jsonrpc"` ID string `json:"id"` Method RPCMethod `json:"method"` Params []interface{} `json:"params,omitempty"` debug bool } func (b *BitcoinService) NewRPCRequest() *RPCRequest { return &RPCRequest{ host: b.host, auth: b.auth, Jsonrpc: "1.0", ID: "curltest", Params: make([]interface{}, 0), } } func (r *RPCRequest) WithDebug() *RPCRequest { r.debug = true return r } func (r *RPCRequest) WithMethod(method RPCMethod) *RPCRequest { r.Method = method return r } func (r *RPCRequest) Call(params ...interface{}) ([]byte, error) { if len(params) > 0 && params != nil { r.Params = append(r.Params, params...) } reqBody, err := json.Marshal(r) if err != nil { fmt.Println(err) return nil, err } if r.debug { log.Printf("%s \n body: \n%s \n", r.Method, string(reqBody)) } payload := bytes.NewReader(reqBody) client := &http.Client{} req, err := http.NewRequest(http.MethodPost, r.host, payload) if err != nil { fmt.Println(err) return nil, err } req.Header.Add("Accept", "text/plain") req.Header.Add("Authorization", r.auth) req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return nil, err } if r.debug { log.Printf("body response: \n%s \n", body) } return body, nil }