Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ctxrwc.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package wrappers
  2. import (
  3. "context"
  4. "net"
  5. "github.com/juju/errors"
  6. )
  7. // CtxReadWriteCloser wraps underlying connection and does management of the
  8. // context and its cancel function.
  9. type CtxReadWriteCloserWithAddr struct {
  10. ctx context.Context
  11. conn ReadWriteCloserWithAddr
  12. cancel context.CancelFunc
  13. }
  14. // Read reads from connection
  15. func (c *CtxReadWriteCloserWithAddr) Read(p []byte) (int, error) {
  16. select {
  17. case <-c.ctx.Done():
  18. return 0, errors.Annotate(c.ctx.Err(), "Read is failed because of closed context")
  19. default:
  20. n, err := c.conn.Read(p)
  21. if err != nil {
  22. c.cancel()
  23. }
  24. return n, err
  25. }
  26. }
  27. // Write writes into connection.
  28. func (c *CtxReadWriteCloserWithAddr) Write(p []byte) (int, error) {
  29. select {
  30. case <-c.ctx.Done():
  31. return 0, errors.Annotate(c.ctx.Err(), "Write is failed because of closed context")
  32. default:
  33. n, err := c.conn.Write(p)
  34. if err != nil {
  35. c.cancel()
  36. }
  37. return n, err
  38. }
  39. }
  40. // Close closes underlying connection.
  41. func (c *CtxReadWriteCloserWithAddr) Close() error {
  42. return c.conn.Close()
  43. }
  44. func (c *CtxReadWriteCloserWithAddr) LocalAddr() *net.TCPAddr {
  45. return c.conn.LocalAddr()
  46. }
  47. func (c *CtxReadWriteCloserWithAddr) RemoteAddr() *net.TCPAddr {
  48. return c.conn.RemoteAddr()
  49. }
  50. // NewCtxRWC returns ReadWriteCloser which respects given context,
  51. // cancellation etc.
  52. func NewCtxRWC(ctx context.Context, cancel context.CancelFunc, conn ReadWriteCloserWithAddr) ReadWriteCloserWithAddr {
  53. return &CtxReadWriteCloserWithAddr{
  54. conn: conn,
  55. ctx: ctx,
  56. cancel: cancel,
  57. }
  58. }