<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adityapathak on Medium]]></title>
        <description><![CDATA[Stories by Adityapathak on Medium]]></description>
        <link>https://medium.com/@adityapathak1189?source=rss-b4c56ab656a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2aM80loBWJquBFfn</url>
            <title>Stories by Adityapathak on Medium</title>
            <link>https://medium.com/@adityapathak1189?source=rss-b4c56ab656a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:53:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityapathak1189/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Five Dysfunctions of a team]]></title>
            <link>https://medium.com/@adityapathak1189/five-dysfunctions-of-a-team-1c07b3f02f53?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c07b3f02f53</guid>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[team-building]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 16:22:42 GMT</pubDate>
            <atom:updated>2023-04-05T16:22:42.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3CYnHO5RI4U6fX9e.png" /></figure><p>“Five Dysfunctions of a Team” is a leadership fable by Patrick Lencioni that explores the common challenges that teams face and provides insights and solutions to overcome them.</p><ol><li><strong>Absence of trust</strong> :- it all starts with the absence of trust between the team. If the team members do not trust each other they will not be comfortable being vulnerable with each other. vulnerability based trust where a person can completely trust the other and can even say things like i don’t know the answer, i need help, i really messed up, i am sorry as what i suggested really got messed up, you are better than me please teach me. It is the most important type of trust for building a high performing team. But most of the time this is not the case and due to lack of trust the 2nd dysfunctions occur which is fear of conflict.</li><li><strong>Fear of conflict</strong> :- fear of conflict arises due to lack of trust. First of all we should understand what is conflict, conflict is nothing but pursuit of truth, to get the best possible answer to the question. If people contradict with each other then that does not mean a bad thing it means they want to find the best possible solution to that problem. if there is a conflict it means the people care for that problem and want to find the best possible solution to it. But most of the time this is not the case and people do not always speak up due to a fear of offending others or damaging relationships and due to this our 3rd dysfunction occurs which is lack of commitment.</li><li><strong>Lack of commitment</strong> :- Lack of commitment arises due to fear of conflict. If people don’t weigh in on a decision they don’t buy into it and thus can lead into passive commitment. As often team members don’t discuss a solution properly due to fear of conflict and due to which whatever path is chosen they passively commit to it. And if asked from them later they say I knew it was not going to work. Lack of commitment is very dangerous for a team. It directly means they are not working actively as they are not connected with the idea or solution and so it’s the responsibility of the team leader to make people speak up their thoughts, as it gives rise to the next dysfunction which is avoidance of accountability.</li><li><strong>Avoidance of accountability</strong> :- This is the worst and most common problem in the team. The type of accountability referred to here is peer to peer as in great team accountability is always peer to peer and not from top management as it gives rise to office politics. The avoidance of accountability rises due to lack of commitment as if people are not committed to the decision they don’t have courage to hold one another accountable. People often make others accountable based on the result or number but not on behaviour. Why? The reason is they are selfish as they don’t want others to blame them for feeling bad, but holding others accountable is important as if you don’t hold them accountable they are not going to learn the consequences of the action. And due to not holding people accountable it gives rise to our last dysfunction which is in attention to result.</li><li><strong>In attention to result</strong> :- In attention to result basically means people don’t care about the result and it occurs due to not lack of accountability. They passively do the work and don’t care about the result and to make them care about the result the only way is to make them accountable and the only way to make them accountable is to make them committed and the only way to make them committed is if they disagree passionately and the only way to do that if they trust each other and are vulnerable.</li></ol><p>Overall, “The Five Dysfunctions of a Team” provides a valuable framework for understanding the common challenges that teams face and offers practical advice for overcoming them. By building trust, engaging in constructive conflict, increasing commitment, and holding each other accountable, teams can achieve their goals and deliver high-quality results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c07b3f02f53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Server in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/http-server-in-golang-a249a8aaad0e?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a249a8aaad0e</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 13:31:45 GMT</pubDate>
            <atom:updated>2023-01-03T13:31:45.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*m1jUUsrJk8I8hAgw" /><figcaption>HTTP Server in Golang</figcaption></figure><h3>Introduction</h3><p>HTTP or Hypertext Transfer Protocol is a communication protocol that is used to transfer data to the World Wide Web. An HTTP server is a program that listens for the incoming requests from the clients and sends back the responses. For example, when you make a request to read this article, an HTTP server is involved in handling that request made by you and returning the content of the article to your web browser.</p><p>Go is a popular programming language known for its simplicity, concurrency support and wide usage in server side applications. One of the core packages in the standard library is <strong>net/http</strong> package, which provides a set of functions and types for building HTTP servers and clients.</p><p>In this article, we will learn how to use the <strong>net/http</strong> package to build an HTTP server in golang. We will cover how to set up the server, handle incoming requests and implement routing. By the end of this article, you will have a solid understanding of how to build an HTTP server in golang and be able to start creating your own web applications.</p><h3>Initial Setup</h3><p>In the initial setup we will be declaring some constants and some utils functions which we will be using in the upcoming sections. The constants which we are going to declare are the HOST and PORT name where the http server can be accessed</p><pre>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>)</pre><p>We will also be declaring a <strong>handleErr</strong> function, whose work is to handle errors if any comes.</p><pre>func handleErr(err error, msg string) {<br>   if err != nil {<br>       log.Println(msg, err)<br>       os.Exit(1)<br>   }<br>}</pre><h3>net/http</h3><p>In Go, most of the HTTP functionality is provided by the <strong>net/http</strong> package from the standard library, while the rest of the network communications is provided by the <strong>net</strong> package, as seen in the previous articles where we have seen how to create a TCP client and server in golang. <strong>net/http</strong> package not only includes the ability to make HTTP requests, but also provides an HTTP server you can use to handle those requests.</p><p>For using <strong>net/http</strong> package we have to import that, we can do that using the import statement.</p><pre>import net/http</pre><h3>Starting a Server</h3><p>A go HTTP server includes two components, first the server that listens for requests coming from HTTP clients and second the request handlers that will respond to those requests. We create multiple handler functions to respond to different requests coming from client. To start a server we use the <strong>http.ListenAndServe</strong> function and tell it to listen for the HTTP requests and then serve them using the handler functions.</p><p>The <strong>ListenAndServe</strong> is a blocking call, it means your program will not continue running after <strong>ListenAndServe</strong> finishes running. However <strong>ListenAndServe</strong> won’t finish running until your program finishes running or the HTTP server is told to shut down. It is important to include error handling because there are some cases where calling <strong>ListenAndServe</strong> can fail.</p><p>The <strong>ListenAndServe</strong> function takes two arguments, first the HOST and PORT which is passed as a string and the second parameter accepts a handler to configure the server for HTTP/2 (Not important for this tutorial), so we pass nil as the second argument. It returns an error if there is any.</p><pre>if err := http.ListenAndServe(HOST+&quot;:&quot;+PORT, nil); err != nil {<br>       log.Println(&quot;error listening to port: &quot;, PORT, &quot; err: &quot;, err)<br>       os.Exit(1)<br>}</pre><h3>Building HTTP Handlers</h3><p>We register the given URL patterns to the handler function. <strong>HandleFunc</strong> function is a convenient way to create handlers.</p><pre>http.HandleFunc(&quot;/&quot;, homeHandler)<br>http.HandleFunc(&quot;/about&quot;, aboutHandler)</pre><p>Here in the above code segment there are two URL paths <strong>“/”</strong> and <strong>“/about”</strong> registered to the handler functions <strong>homeHandler</strong> and <strong>aboutHandler</strong> respectively which we will declare in the upcoming sections. So when the clients hit at any specific path the respective handler function will respond.</p><p>Both of the handler function has the same function signature, where they accept the same arguments, an <strong>http.ResponseWriter</strong> value and an <strong>*http.Request</strong> value. The <strong>http.ResponseWriter</strong> value is used to control the response information being sent back to the client that made the request. The <strong>*http.Request</strong> value is used to get information about requests that came to the server such as the request type (GET, POST … etc)</p><pre>func handlerName(w http.ResponseWriter, r *http.Request) {<br>  …<br>}<br><br>Eg:<br>func homeHandler(w http.ResponseWriter, r *http.Request) {<br>  …<br>}</pre><h4>HTTP Status Codes</h4><p>We can set the HTTP response status codes indicating whether a specific request has been successfully fulfilled.</p><p>The response codes are grouped in five class:</p><ol><li>Information responses (100–199)</li><li>Successful responses (200–299)</li><li>Redirects (300–399)</li><li>Client errors (400–499)</li><li>Server errors (500–599)</li></ol><p>The response code is written with the WriteHeader function</p><pre>w.WriteHeader(http.StatusOK)<br>w.WriteHeader(http.StatusNotFound)</pre><p>Here http.StatusOK represents status code 200 and http.StatusNotFound refers to 404.</p><h4>URL Path</h4><p>We can retrieve the URL path value from the request and can check if the path entered is valid or not.</p><pre>if r.URL.Path != &quot;/&quot; {<br>       w.WriteHeader(http.StatusNotFound)<br>       w.Write([]byte(&quot;status not found, please check url&quot;))<br>       return<br>}</pre><h4>Query Param</h4><p>A query string is the part of the URL that assigns values to specified parameters.</p><p>Eg:</p><pre>https://localhost:8080/users?name=Aditya&amp;role=SDE</pre><p>Query param starts with ? character and multiple query params are separated by &amp; character, as in the above case the name and role params. The name param has a value “Aditya” and the role param has value “SDE”.</p><pre>val, ok := r.URL.Query()[&quot;name&quot;]</pre><p>The value can be extracted from the query param using <strong>r.URL.Query()[“name of param”]</strong></p><h4>Retrieving Form Data</h4><p>Forms were widely used earlier to send data to a server but they aren’t popular now, but still sometimes we use it. We can extract the value from the form using <strong>PostFormValue</strong> method on the <strong>*http.Request</strong>.</p><pre>name := r.PostFormValue(&quot;name&quot;)</pre><p>Here in the above code segment we are extracting the value of the name field and storing it in variable.</p><h4>Process different request methods</h4><p>We can also return different responses based on the type of method the request has made. Using <strong>r.Method</strong> we can get the type of method. Eg: we can return separate responses for GET and POST methods</p><pre>switch r.Method {<br>   case &quot;GET&quot;:<br>       fmt.Fprintln(w, &quot;home handler get request&quot;)<br>   case &quot;POST&quot;:<br>       fmt.Fprintln(w, &quot;home handler post request&quot;)<br>   default:<br>       fmt.Fprintln(w, &quot;home handler default request&quot;)<br>}</pre><p>In the above code segment a switch statement is used for handling different request methods.</p><p>The complete home handler code:</p><pre>func homeHandler(w http.ResponseWriter, r *http.Request) {<br>   if r.URL.Path != &quot;/&quot; {<br>       w.WriteHeader(http.StatusNotFound)<br>       w.Write([]byte(&quot;status not found, please check url&quot;))<br>       return<br>   }<br>   switch r.Method {<br>   case &quot;GET&quot;:<br>       fmt.Fprintln(w, &quot;home handler get request&quot;)<br>   case &quot;POST&quot;:<br>       fmt.Fprintln(w, &quot;home handler post request&quot;)<br>   default:<br>       fmt.Fprintln(w, &quot;home handler default request&quot;)<br>   }<br>}</pre><h3>Complete Code</h3><pre>package main<br><br>import (<br>   &quot;encoding/json&quot;<br>   &quot;fmt&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>)<br><br>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>)<br><br>type Data struct {<br>   Name string `json:&quot;name&quot;`<br>   Age  int    `json:&quot;age&quot;`<br>}<br><br>func homeHandler(w http.ResponseWriter, r *http.Request) {<br>   if r.URL.Path != &quot;/&quot; {<br>       w.WriteHeader(http.StatusNotFound)<br>       w.Write([]byte(&quot;status not found, please check url&quot;))<br>       return<br>   }<br><br>   switch r.Method {<br>   case &quot;GET&quot;:<br>       fmt.Fprintln(w, &quot;home handler get request&quot;)<br>   case &quot;POST&quot;:<br>       fmt.Fprintln(w, &quot;home handler post request&quot;)<br>   default:<br>       fmt.Fprintln(w, &quot;home handler default request&quot;)<br>   }<br>}<br><br>func aboutHandler(w http.ResponseWriter, r *http.Request) {<br>   if r.URL.Path != &quot;/about&quot; {<br>       w.WriteHeader(http.StatusNotFound)<br>       w.Write([]byte(&quot;status not found, please check url&quot;))<br>       return<br>   }<br>   w.WriteHeader(http.StatusOK)<br>   w.Write([]byte(&quot;about handler&quot;))<br>}<br><br>func jsonHandler(w http.ResponseWriter, r *http.Request) {<br>   if r.URL.Path != &quot;/json&quot; {<br>       w.WriteHeader(http.StatusNotFound)<br>       w.Write([]byte(&quot;status not found, please check url&quot;))<br>       return<br>   }<br>   data := Data{<br>       Name: &quot;Aditya Pathak&quot;,<br>       Age:  22,<br>   }<br>   resp, err := json.Marshal(data)<br>   handleErr(err, &quot;error parsing data&quot;)<br>   w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>   w.Write(resp)<br>}<br><br>func main() {<br>   http.HandleFunc(&quot;/&quot;, homeHandler)<br>   http.HandleFunc(&quot;/about&quot;, aboutHandler)<br>   http.HandleFunc(&quot;/json&quot;, jsonHandler)<br><br>   if err := http.ListenAndServe(HOST+&quot;:&quot;+PORT, nil); err != nil {<br>       fmt.Println(&quot;error occurred while listening to port: &quot;, PORT, &quot; err: &quot;, err)<br>       os.Exit(1)<br>   }<br>}<br><br>func handleErr(err error, msg string) {<br>   if err != nil {<br>       fmt.Println(msg, err)<br>       os.Exit(1)<br>   }<br>}</pre><p>Thanks for reading the article.</p><p><strong>Next Article</strong>: HTTP Client in Golang [6th Jan].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a249a8aaad0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Go Workspace]]></title>
            <link>https://medium.com/@adityapathak1189/introduction-to-go-workspace-3eff79cc5127?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eff79cc5127</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[workspace]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 11:14:53 GMT</pubDate>
            <atom:updated>2023-01-01T11:14:53.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*TERSckWlSUnKYiW8" /><figcaption>Go Workspace</figcaption></figure><p><strong>Go workspace</strong> was introduced with <strong>Go 1.18</strong>. It allows us to work with multiple modules simultaneously without having to edit go.mod files for each module. Each module within a workspace is treated as a root module when resolving dependencies. We create a go workspace and work inside it.</p><p>Workspace can be initialised using:</p><pre>go work init</pre><p>It will create a <strong>go.work</strong> file which is there in the parent directory which will put the go command in the workspace mode. In the workspace mode <strong>go.work</strong> file will be used to determine the set of main modules used as root for module resolution instead of using go.mod file to specify the single main module.</p><p>Let’s understand it by example :</p><p>We have created a workspace directory (you can name it anything, not necessarily workspace only) and inside workspace we have created a helloWorld directory and initialised it as a module.</p><pre>mkdir workspace <br>cd workspace<br>mkdir helloWorld<br>cd helloWorld<br>go mod init helloWorld</pre><p>Now we create a main.go file and write a code to reverse a string using the stringutils package.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br><br> &quot;golang.org/x/example/stringutil&quot;<br>)<br><br>func main() {<br> fmt.Println(stringutil.Reverse(&quot;Hello World&quot;))<br>}</pre><p>And when we run it it will print “Hello World” in reverse order. Now we want to modify the stringutil package that our code depends on.</p><p>Until now we had to do it using the replace directive in the go.mod file, but now we will do it using workspace. So let’s create our workspace in the workspace directory using the go work init command and it will create a <strong>go.work</strong> file, and we will add the module helloWorld in it using command :</p><pre>go work use ./helloWorld</pre><p>And it will update our go.work file</p><pre>go 1.18<br><br>use ./helloWorld</pre><p>Now let’s download the stringutil package and modify the Reverse function</p><pre>git clone https://go.googlesource.com/example  </pre><p>And let’s change the Reverse function inside <strong>example/stringutil/reverse.go</strong> to return “Hello World” with the string rather than reversing the string.</p><p><strong>example/stringutil/reverse.go</strong></p><pre>func Reverse(s string) string {<br> return fmt.Sprintf(&quot;Hello World %s&quot;, s)<br>}</pre><p>And finally add the example package to the workspace using the command</p><pre>go work use ./example</pre><p>The modified go.work file is</p><pre>go 1.18<br><br>use (<br> ./example<br> ./helloWorld<br>)</pre><p>And now when we run the main.go file in helloWorld it will return Hello World along with the string passed.</p><p>That was about go workspace, for large scale projects we use go workspace. For more such article comment down your suggestions and follow the account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eff79cc5127" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP Client in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/tcp-client-in-golang-a67f88a31326?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67f88a31326</guid>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 14:36:15 GMT</pubDate>
            <atom:updated>2022-12-29T14:46:41.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*6P8VF6qxrFFjm-RJ" /><figcaption>TCP client in golang</figcaption></figure><p>This article is an extension of previous article in which we saw how to create a <strong>TCP</strong> server in golang which can communicate with concurrent users. In this article we are going to see how to make a <strong>TCP</strong> client in golang that sends the request to the server and consumes the response received back, it is similar to client and server terminal chat where until the client doesn’t quit the communication is taking place. We will be using the net package from the standard library, which is a set of core packages that enhance and extend the language. We don’t need to build our own package or download any from a third party.</p><p>For using the net package use the import statement to import the package.</p><pre>import &quot;net&quot; </pre><p>We will define some variables which will be required to make a tcp connection, and as the variables are not going to change in the future so we will declare them as constants.</p><pre>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>   TYPE = &quot;tcp&quot;<br>)</pre><p>The above declared constants are HOST which will be <strong>localhost</strong> in this case, the PORT number where we can access the server here it is <strong>8080</strong> and the TYPE of network that will be used here it will be <strong>tcp</strong>.</p><p>We will create a util function named checkErr where we pass the error and a error message string as an argument and it handles the error.</p><pre>func checkErr(err error, msg string) {<br>   if err != nil {<br>       fmt.Println(&quot;error: &quot;, msg, &quot; &quot;, err)<br>       os.Exit(1)<br>   }<br>}</pre><p>For connecting with the desired server we use the <strong>Dial</strong> function from the <strong>net</strong> package which takes two arguments the first being the network type and the second being the address. <strong>Dial</strong> function returns <strong>net.Conn</strong> and the <strong>error</strong>, we handle the error in the separate <strong>checkErr</strong> function. We use the <strong>defer</strong> keyword to close the connection when the program is terminated.</p><pre>conn, err := net.Dial(TYPE, HOST+&quot;:&quot;+PORT)<br>defer conn.Close()<br>checkErr(err, &quot;Unable to connect&quot;)</pre><p>After connecting with the server we read the response from the server using the <strong>Read</strong> function which takes a slice of byte as argument where it stores the data.</p><pre>buf := make([]byte, 1024)<br>_, err = conn.Read(buf)<br>checkErr(err, &quot;Error reading data&quot;)<br>fmt.Println(string(buf))</pre><p>For sending messages to the server we first take the input message from the terminal using the functions from the bufio package. We first create a Reader and then read the data from the terminal using the <strong>ReadString</strong> function.</p><pre>msgReader := bufio.NewReader(os.Stdin)<br>fmt.Print(&quot;Enter your text: &quot;)<br>msg, _ := msgReader.ReadString(&#39;\n&#39;)</pre><p>After getting the message we use the <strong>Write</strong> function to send the message to the server.</p><pre>conn.Write([]byte(msg))</pre><p>Here is the full code for the same.</p><pre>package main<br><br>import (<br>   &quot;bufio&quot;<br>   &quot;fmt&quot;<br>   &quot;net&quot;<br>   &quot;os&quot;<br>)<br><br>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>   TYPE = &quot;tcp&quot;<br>)<br><br>func main() {<br>   fmt.Println(&quot;!! TCP Client in golang !!&quot;)<br><br>   conn, err := net.Dial(TYPE, HOST+&quot;:&quot;+PORT)<br>   defer conn.Close()<br>   checkErr(err, &quot;Unable to connect&quot;)<br><br>   buf := make([]byte, 1024)<br>   _, err = conn.Read(buf)<br>   checkErr(err, &quot;Error reading data&quot;)<br>   fmt.Println(string(buf))<br><br>   for {<br>       msgReader := bufio.NewReader(os.Stdin)<br>       fmt.Print(&quot;Enter your text: &quot;)<br>       msg, _ := msgReader.ReadString(&#39;\n&#39;)<br>       conn.Write([]byte(msg))<br>   }<br>}<br><br>func checkErr(err error, msg string) {<br>   if err != nil {<br>       fmt.Println(&quot;error: &quot;, msg, &quot; &quot;, err)<br>       os.Exit(1)<br>   }<br>}</pre><p>Thanks for reading the article, please add your valuable feedback in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67f88a31326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP Server in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/tcp-server-in-golang-3c75766a8b08?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c75766a8b08</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 12:12:34 GMT</pubDate>
            <atom:updated>2022-12-29T11:34:33.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*cg5Fr65lI2UyIBbZ" /><figcaption>TCP Server in Golang</figcaption></figure><p>In this tutorial we are going to see how to make a simple <strong>TCP</strong> server in golang that accepts the incoming requests from concurrent clients and responds with a greeting message. We will be using the <strong>net</strong> package from the standard library, which is a set of core packages that enhance and extend the language. We don’t need to build our own package or download any from a third party.</p><p>For using the <strong>net</strong> package use the import statement to import the package.</p><pre>import &quot;net&quot; </pre><p>We will define some variables which will be required to make a tcp connection, and as the variables are not going to change in the future so we will declare them as constants.</p><pre>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>   TYPE = &quot;tcp&quot;<br>)</pre><p>The above declared constants are HOST which will be <strong>localhost</strong> in this case, the PORT number where we can access the server here it is <strong>8080</strong> and the TYPE of network that will be used here it will be <strong>tcp</strong>.</p><p>The main task of the server is to listen to the request of client’s and so we will use the <strong>Listen</strong> function from the net package to make a listener which listens to the request of the client’s. The Listen function takes the Type of network (such as tcp, tcp4, etc), the host and the port name as the arguments.</p><pre>listener, err := net.Listen(TYPE, HOST+&quot;:&quot;+PORT)<br>if err != nil {<br> log.Print(&quot;error occurred&quot;, err)<br> os.Exit(1)<br>}</pre><p>The <strong>Listen</strong> function returns the <strong>listener</strong> and the <strong>error</strong>, we handle the error if there will be any. Later we also need to close the listener when the server is terminated so we use <strong>defer</strong> keyword to close the listener.</p><pre>defer listener.Close()</pre><p>The next step is to listen to the continuous connections which will be coming to the server and we do that using the infinite for loop.</p><pre>for {<br>       conn, err := listen.Accept()<br>       if err != nil {<br>           log.Print(&quot;Error accepting connection: &quot;, err)<br>           os.Exit(1)<br>       }<br>       // handling incoming requests.<br>   }</pre><p>Here we accept the request of the client using the <strong>Accept</strong> function which will return two values of type <strong>net.Conn</strong> and <strong>error</strong> respectively. We handle the error if there is any.</p><p>To handle any incoming request we create a <strong>handleConnection</strong> function, we handle the connections in separate <strong>goroutine</strong></p><pre>go handleConnection(conn)</pre><pre>func handleConnection(conn net.Conn) {<br>   buffer := make([]byte, 1024)<br>   if _, err := conn.Read(buffer); err != nil {<br>       if err == io.EOF {<br>           log.Println(&quot;terminating&quot;)<br><br>       }<br>       log.Panic(&quot;error occurred&quot;, err)<br>   }<br>   conn.Write([]byte(&quot;Hello User\r\n&quot;))<br>   conn.Close()<br>}</pre><p>In the above <strong>handleConnection</strong> function we pass the argument of type <strong>net.Conn</strong> which we receive from the <strong>Accept</strong> function and a buffer is created of size 1024 to store the incoming data. The data is read from the client using the <strong>Read</strong> function and is stored in the buffer variable. To send data to the client we use the <strong>Write</strong> function which writes data to the client and at the end we close the connection using the <strong>Close</strong> function.</p><p>The full source code for the above program:</p><pre>package main<br><br>import (<br>   &quot;io&quot;<br>   &quot;log&quot;<br>   &quot;net&quot;<br>)<br><br>const (<br>   HOST = &quot;localhost&quot;<br>   PORT = &quot;8080&quot;<br>   TYPE = &quot;tcp&quot;<br>)<br><br>func main() {<br>   log.Println(&quot;Simple TCP server in Go&quot;)<br>   listen, err := net.Listen(TYPE, HOST+&quot;:&quot;+PORT)<br>   if err != nil {<br>       log.Panic(&quot;Failed to bind to port 8080 &quot;, err)<br>   }<br>   defer listen.Close()<br><br>   for {<br>       conn, err := listen.Accept()<br>       if err != nil {<br>           log.Panic(&quot;Error accepting connection: &quot;, err)<br>       }<br>       go handleConnection(conn)<br>   }<br>}<br><br>func handleConnection(conn net.Conn) {<br>   buffer := make([]byte, 1024)<br>   if _, err := conn.Read(buffer); err != nil {<br>       if err == io.EOF {<br>           log.Println(&quot;terminating&quot;)<br>       }<br>       log.Panic(&quot;error occurred&quot;, err)<br>   }<br>   conn.Write([]byte(&quot;Hello User\r\n&quot;))<br>   conn.Close()<br>}</pre><p>Thanks for reading the article, your valuable feedback is highly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c75766a8b08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflection in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/reflection-in-golang-9e2641fd5ea4?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2641fd5ea4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 11:42:48 GMT</pubDate>
            <atom:updated>2022-12-25T11:42:48.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*UfPK0k2hHAprlrek78q46A.png" /><figcaption>Reflection in Go</figcaption></figure><p><strong>Reflection</strong>: It is the ability of the program to introspect and analyse its structure during runtime. Or we can say that it is a set of functions which are used to extract the data about a variable during run time. We can get the type and value information during runtime. It implements reflection with the reflect package which provides types and methods for inspecting portions of the interface structure and even modifying values at the runtime.</p><p>First we need to import the reflect package.</p><pre>import &quot;reflect&quot;</pre><p>The <strong>reflect.Type</strong> and <strong>reflect.Value</strong> types provide methods to access portions of the interface. Type focuses on data about type and value focuses on the data about the value. The <strong>Kind</strong> method focuses on the representation of the type of a type.</p><pre>t := reflect.TypeOf(s)<br>v := reflect.ValueOf(s)<br>k := t.Kind()</pre><p>Here is the full code for the same, taking the example of the Shape, Rectangle and Circle from previous (Interface) part.</p><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;math&quot;<br>   &quot;reflect&quot;<br>)<br><br>type Shape interface {<br>    area() float64<br>    perimeter() float64<br>}<br><br>type Rectangle struct {<br>    length, width float64<br>}<br><br>type Circle struct {<br>    radius float64<br>}<br><br>func (r Rectangle) area() float64 {<br>    return r.length * r.width<br>}<br><br>func (c Circle) area() float64 {<br>    return math.Pi * c.radius * c.radius<br>}<br><br>func (r Rectangle) perimeter() float64 {<br>    return 2 * (r.length + r.width)<br>}<br><br>func (c Circle) perimeter() float64 {<br>    return 2 * math.Pi * c.radius<br>}<br><br>func details(s Shape) {<br>   t := reflect.TypeOf(s)<br>   v := reflect.ValueOf(s)<br>   k := t.Kind()<br>   fmt.Println(&quot;type: &quot;, t, &quot; vlaue: &quot;, v, &quot; kind: &quot;, k)<br>}<br><br>func main() {<br>   var s Shape<br>   s = Rectangle{length: 12.2, width: 8.7}<br>   details(s)<br>   s = Circle{radius: 2.4}<br>   details(s)<br>}</pre><p>The output is</p><pre>type: main.Rectangle vlaue: {12.2 8.7} kind: struct<br>type: main.Circle vlaue: {2.4} kind: struct</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2641fd5ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/generics-in-golang-541e059e5974?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/541e059e5974</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 12:56:17 GMT</pubDate>
            <atom:updated>2022-12-23T12:56:17.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*7R25YEb_ohAQ7EcdW6ToZg.png" /></figure><p>Generics was released with Go version 1.18. It basically means parameterized types, meaning it allows programmers to write code where the type can be specified later because the type is not relevant at that point. In other words, while writing some code you don’t provide the type of values. These type values are passed later.</p><p>Its syntax is:</p><pre>func funcName[type_parameter type_constraint](… type_parameter) type_parameter {<br> …<br>}<br><br>func funcName[T any](… T) T {<br> …<br>}<br><br>func funcName[T interface{}](… T) T {<br> …<br>}</pre><p>Here <strong>T</strong> is the <strong>type parameter</strong> and <strong>any</strong> is the <strong>type constraint</strong> which can be any interface means unlimited values, here <strong>any</strong> represents an <strong>empty interface</strong>.</p><p>In the example below there are two functions, the first returnFirst takes any constraint means we can pass anything not specific int or float and it returns the first argument. The second function namely returnFloatFirst only takes float64 type as the argument and if we pass any other type then it will throw an error. In the main function you can see that the returnFirst function we can call without specifying the constraint type and it works, it is due to <strong>type inference</strong>.</p><pre>func returnFirst[T any](a T, b T) T {<br>  return a <br>}<br><br>func returnFloatFirst[T float64](a T, b T) T {<br>  return a <br>}<br><br>func main() {<br>  fmt.Println(returnFirst[int](1,3))<br>  fmt.Println(returnFirst(1,3))<br>  fmt.Println(returnFirst[float64](1.8,3.9))<br>  fmt.Println(returnFirst(1.8,3.9))<br>  fmt.Println(returnFirst(&quot;a&quot;,&quot;b&quot;))<br>  fmt.Println(returnFloatFirst(1.2,3.4))<br>}</pre><p>Go 1.18 comes with <strong>type inference</strong> which helps us to write code that calls generic functions without explicit types.</p><p>Let’s take another example, say you have to calculate the sum of all the elements of the array, now if i say that each time i change the type of data the array stores then the implementation of the function will remain the same but you have to write a separate function to accommodate different types, so let’s write a generic function which adds up the elements of the array and returns the sum.</p><pre>func sumAll[T any](arr []T) T {<br>  var s T<br>  for _, ele := range arr {<br>    s += ele<br>  }<br>  return s<br>}<br><br>func main() {<br>  fmt.Println(&quot;sum: &quot;, sumAll([]int{1, 2, 3, 5, 6}))<br>}</pre><p>When you run the above code it will give an error:</p><pre>$ go run main.go<br>./main.go:6:9: invalid operation: operator + not defined on a (variable of type T constrained by any)</pre><p>It’s because <strong>any</strong> constraint can hold any value, here in the above case it is <strong>int</strong> but it can be anything and there is a chance that operator might not work for that particular type so it is throwing an error. To fix this issue we use <strong>type set</strong> where we define a custom constraint with the help of interface and use that at the place of type constraint. We declare a set of types for that constraint and we have to use only those types.</p><p>The syntax to define a custom constraint is:</p><pre>type customConstraint interface {<br>  type1 | type2 | type3 …<br>} <br><br>type cusConstraint interface {<br>  float64 | int | string<br>}</pre><p>We can also use the <strong>constraints</strong> package which defines a set of useful constraints to be used with the parameters</p><p>First we have to install the constraints package.</p><pre>$ go get golang.org/x/exp/constraints</pre><p>Some constraints from the package.</p><pre>type Signed interface {<br>  ~int | ~int8 | ~int16 | ~int32 | ~int64<br>}<br><br>type Unsigned interface {<br>  ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr<br>}<br><br>type Integer interface {<br>  Signed | Unsigned<br>}<br><br>type Float interface {<br>  ~float32 | ~float64<br>}<br><br>type Complex interface {<br>  ~complex64 | ~complex128<br>}<br><br>type Ordered interface {<br>  Integer | Float | ~string<br>}</pre><p>So now let’s create a custom constraint which can have support for <strong>float64</strong> and <strong>int</strong> types of data, and use it at the place of any constraint.</p><pre>type constraint interface {<br>  ~float64 | int<br>}<br><br>func sumAll[T constraint](arr []T) T {<br>  var s T<br>  for _, ele := range arr {<br>    s += ele<br>  }<br>  return s<br>}<br><br>func main() {<br>  fmt.Println(&quot;sum: &quot;, sumAll([]int{1, 2, 3, 5, 6}))<br>  fmt.Println(&quot;sum: &quot;, sumAll([]float64{1.2, 2.1, 3.8, 5.4}))<br>}</pre><p>The above code works.</p><p>Thanks for making up to this part, please add your valuable comments and suggestions so that i can make the article more interactive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541e059e5974" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interfaces in Golang]]></title>
            <link>https://medium.com/@adityapathak1189/interfaces-in-golang-59856589151c?source=rss-b4c56ab656a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/59856589151c</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[interface-in-go]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Adityapathak]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 17:32:54 GMT</pubDate>
            <atom:updated>2022-12-21T17:32:54.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*XwSbg2OGJgbwbBju" /><figcaption>Interfaces in go</figcaption></figure><p>Interfaces in golang are different from those from other languages, as interface in go is a custom type and also a collection of methods. Interface is abstract so you are not allowed to create an instance but you can create a variable of it and can assign it with type values that have the methods the interface requires.</p><p>To define an interface we use <strong>type</strong> Name <strong>interface</strong> syntax where interface is a reserved key and only used to define an interface. Inside the definition we can declare the methods and their blueprint of the parameters and the return type.</p><p>Below is a proper syntax to define an interface with the set of methods and how to declare them.</p><pre>type nameOfInterface interface {<br>    func_1() return_type<br>    func_2(arg type) return_type<br>    ...<br>}</pre><p>An example of the above:</p><pre>type Animal interface {<br>   Speak() <br>   Run()<br>   NumOfLegs() int<br>}</pre><p>Here is an animal interface which has three methods: the first two don’t have any return type and the third has a return type of int.</p><p>Below is the code for how to implement an interface in golang with the example of shapes and its properties. We first have to define the structs and implement the methods of this struct. Here two structs namely <strong>Rectangle</strong> and <strong>Circle</strong> have been declared and the methods namely <strong>area</strong> and <strong>perimeter</strong> have been implemented for them. Then we can use the variable of these struct types for interface as they satisfy the methods requirement. We can also pass those variables at the place of interface Shape requirement as shown below, where in the <strong>details</strong> function which requires a <strong>Shape</strong> type we have passed an argument of type <strong>Rectangle</strong> and it works. In the next article we will discuss why we can do that when we will learn about <strong>duck typing</strong>.</p><pre>package main<br>import (<br>    &quot;fmt&quot;<br>    &quot;math&quot;<br>)<br><br>type Shape interface {<br>    area() float64<br>    perimeter() float64<br>}<br><br>type Rectangle struct {<br>    length, width float64<br>}<br><br>type Circle struct {<br>    radius float64<br>}<br><br>func (r Rectangle) area() float64 {<br>    return r.length * r.width<br>}<br><br>func (c Circle) area() float64 {<br>    return math.Pi * c.radius * c.radius<br>}<br><br>func (r Rectangle) perimeter() float64 {<br>    return 2 * (r.length + r.width)<br>}<br><br>func (c Circle) perimeter() float64 {<br>    return 2 * math.Pi * c.radius<br>}<br><br>func details(s Shape) {<br>    fmt.Println(s.area())<br>}<br><br>func main() {<br>    var s Shape<br>    r := Rectangle{<br>        length: 12.2,<br>        width: 2.6,<br>    }<br>    details(r)<br>    s = Circle{radius: 10.2}<br>    fmt.Println(s.area())<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59856589151c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>