package tcp import ( "encoding/json" "net" ) type ShutdownFunc func() error type SocketConn struct { conn net.Conn Shutdown ShutdownFunc } func (self *SocketConn) Read() ([]byte, error) { return readFrame(self.conn) } func (self *SocketConn) Write(b []byte) error { return sendFrame(self.conn, b) } func Dial(addr, route string) (*SocketConn, error) { conn, err := net.Dial("tcp", addr) if err != nil { return nil, err } header := RequestHeader{ Method: MethodSOCKET, Route: route, } rawHeader, err := json.Marshal(header) if err != nil { return nil, err } if err := sendFrame(conn, rawHeader); err != nil { return nil, err } // Empty body if err := sendFrame(conn, []byte{}); err != nil { return nil, err } return &SocketConn{ conn: conn, Shutdown: func() error { return conn.Close() }, }, nil }