Hope you are enjoying our blog on go routines and concurrency. In this blog, we will basically cover how you will control the channel. To make this complex problem easy I will make a control flow that you can use in your program. As we do instead of theoretic we will take it practically.
This is a blog, where I am sharing patterns that can be used in “golang” for go routines.
Let me example of each component now.
The server could be anything not necessarily HTTP which is serving data. Therefore it is a struct here where we have created two value msgch to send a message the message to the channel and quitch which is to inform that no more messages are there so we can close the connection.
After creating one server we will start the server and once the server is started we will inform the server about the next plan. Here we are calling the loop function once it is starting. In your project, you can call the appropriate function as per your project requirement. As this is a template to control channels.
In the loop function, we will create two loops one For and the other Select loop so for loop we will keep on looping over the select loop so that it keeps reading incoming messages from the server. And if it receives a close message then it just comes out of the loop function.
So when the case is a new message then this program will call the handle message function and pass the message as value to that integer.
If the case is quitch then it will break the Mainloop and come out from for and select loop.
We are just printing the message received from the server. As per your program needs you can play as per your program requirement.
Ok so, this is all practical here, we are all set for a basic channel setup for go routines.
Let us understand the main body from where our program will run
We are creating a new server say server and then using the go routine we are starting the server simultaneously. And sending the message to the server which could be received from the actual server in the program.
Check the source code in the linked repository.
I hope you have understood the topic. I am keeping this blog a little bit short as in the next blog, I will be covering Mutexes, race conditions, and Automic values.
Keep reading, and grow the Go community. If you face any issues in development feel free to contact our Golang developers.