Skip to content

Instantly share code, notes, and snippets.

@myaaaaa-chan
Created March 30, 2018 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myaaaaa-chan/4c75f112c32bbee6bb410036dd839cb8 to your computer and use it in GitHub Desktop.
Save myaaaaa-chan/4c75f112c32bbee6bb410036dd839cb8 to your computer and use it in GitHub Desktop.
gethのPub/Subのサンプル
package main
import (
"encoding/json"
"log"
"net/url"
"os"
"os/signal"
"github.com/gorilla/websocket"
)
// {"id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}
type SubscribeMsg struct {
Id int32 `json:"id"`
Method string `json:"method"`
Params []string `json:"params"`
}
// {"jsonrpc":"2.0","id":2,"result":"0x9ce59a13059e417087c02d3236a0b1cc"}
type SubscribeResponseMsg struct {
JsonRpc string `json:"jsonrpc"`
Id int32 `json:"id"`
Result string `json:"result"`
}
func main() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u, err := url.Parse("ws://127.0.0.1:8546")
if err != nil {
log.Fatal(err)
}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
newPedingTranSubMsg := SubscribeMsg{
Id: 1,
Method: "eth_subscribe",
Params: []string{"newPendingTransactions"},
}
sendMsg(c, newPedingTranSubMsg)
for {
select {
case <-done:
return
case <-interrupt:
log.Println("interrupt")
return
}
}
}
func sendMsg(ws *websocket.Conn, msg interface{}) {
ws.WriteJSON(msg)
b, _ := json.Marshal(msg)
log.Printf("Send: %#v\n", string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment