user2089648
user2089648

Reputation: 1416

Golang prevent channel from blocking

I am building a server that uses websockets.
Currently every connected client uses two goroutines. One for reading and one for writing. The writing goroutine basically listens to a channel for messages it should send and then tries to deliver them.

type User struct{
    send chan []byte
    ...
}

func (u *User) Send(msg []byte){
    u.send <- msg
}

Problem is, that a read from client A may cause a write to client B. Suppose the connection to B has some problems however (e.g. very slow) and it's send channel is already full. Current behaviour is, that trying to add a message to the channel now starts blocking, until something is removed from the channel. This means, that now A waits until B's buffer is no longer full.

I want to solve it somewhat like this:

func (u *User) Send(msg []byte) err{
    u.send, err <- msg
    if err != nil{
        //The channels buffer is full.
        //Writing currently not possible.
        //Needs appropriate error handling.
        return err
    }
    return nil
}

Basically instead of blocking I want error handling in case the buffer is full. How do I achieve that best?

Upvotes: 6

Views: 4235

Answers (1)

user2089648
user2089648

Reputation: 1416

As ThunderCat pointed out in his comment the solution is

func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}

Upvotes: 6

Related Questions