Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go Web Development Cookbook

You're reading from   Go Web Development Cookbook Build full-stack web applications with Go

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher Packt
ISBN-13 9781787286740
Length 338 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Arpit Aggarwal Arpit Aggarwal
Author Profile Icon Arpit Aggarwal
Arpit Aggarwal
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Creating Your First Server in Go 2. Working with Templates, Static Files, and HTML Forms FREE CHAPTER 3. Working with Sessions, Error Handling, and Caching in Go 4. Writing and Consuming RESTful Web Services in Go 5. Working with SQL and NoSQL Databases 6. Writing Microservices in Go Using Micro – a Microservice Toolkit 7. Working with WebSocket in Go 8. Working with the Go Web Application Framework – Beego 9. Working with Go and Docker 10. Securing a Go Web Application 11. Deploying a Go Web App and Docker Containers to AWS 12. Other Books You May Enjoy

Writing data to a TCP connection

Another common, as well as important, scenario in any web application is to send the data back to the client or responding to the client. Go provides a convenient way to write a message on a connection as bytes, which we will be covering in this recipe.

Getting ready...

As we have already created a TCP server that reads incoming connection data in the previous recipe, we will just update it to write the message back to the client.

How to do it...

In this recipe, we are going to update the handleRequest method in the program to write data back to the client. Perform the following steps:

  1. Create tcp-server-write-data.go and copy the following content:
package main
import
(
"bufio"
"fmt"
"log"
"net"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
CONN_TYPE = "tcp"
)
func main()
{
listener, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
if err != nil
{
log.Fatal("Error starting tcp server : ", err)
}
defer listener.Close()
log.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
for
{
conn, err := listener.Accept()
if err != nil
{
log.Fatal("Error accepting: ", err.Error())
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn)
{
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil
{
fmt.Println("Error reading: ", err.Error())
}
fmt.Print("Message Received:", string(message))
conn.Write([]byte(message + "\n"))
conn.Close()
}
  1. Run the program with the following command:
$ go run tcp-server-write-data.go

How it works...

Once we run the program, the TCP server will start locally listening on port 8080. Execute an echo command from the command line, as follows:

$ echo -n "Hello to TCP server\n" | nc localhost 8080

This will give us the following response from the server:

Hello to TCP server

Let’s look at the changes we introduced in this recipe to write data to the client. Everything in handleRequest is exactly the same as in the previous recipe except we introduced a new line that writes data as a byte array to the connection, as follows:

func handleRequest(conn net.Conn) 
{
...
conn.Write([]byte(message + "\n"))
...
}
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime