github.com/mailgun/holster/v4@v4.20.0/udp/client.go (about) 1 package udp 2 3 import ( 4 "fmt" 5 "net" 6 "time" 7 ) 8 9 type Client struct { 10 conn *net.UDPConn 11 addr net.Addr 12 } 13 14 func NewClient(address string) (*Client, error) { 15 addr, err := net.ResolveUDPAddr("udp", address) 16 if err != nil { 17 return nil, fmt.Errorf("while resolving Upstream address: %w", err) 18 } 19 20 conn, err := net.DialUDP("udp", nil, addr) 21 if err != nil { 22 return nil, fmt.Errorf("while dialing udp '%s' - %w", addr.String(), err) 23 } 24 return &Client{ 25 conn: conn, 26 addr: addr, 27 }, nil 28 } 29 30 func (c *Client) Recv(b []byte, timeout time.Duration) (int, net.Addr, error) { 31 deadline := time.Now().Add(timeout) 32 if err := c.conn.SetReadDeadline(deadline); err != nil { 33 return 0, nil, err 34 } 35 return c.conn.ReadFrom(b) 36 } 37 38 func (c *Client) Send(b []byte) (int, error) { 39 return c.conn.Write(b) 40 } 41 42 func (c *Client) Close() { 43 c.conn.Close() 44 }