create a tcp server in go

To create a TCP server in Go, you can use the net package which provides support for TCP socket programming in Go. Here's a sample code for a simple TCP server:

main.go
package main

import (
	"fmt"
	"net"
)

func main() {
	// Listen for incoming connections
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println(err)
		return
	}
	// Close the listener when the application closes
	defer l.Close()
	fmt.Println("Listening on port 8080")
	for {
		// Wait for a connection
		conn, err := l.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		// Handle the connection in a new goroutine
		go handleRequest(conn)
	}
}

func handleRequest(conn net.Conn) {
	// Make a buffer to hold incoming data
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer
	reqLen, err := conn.Read(buf)
	if err != nil {
		fmt.Println("Error reading:", err.Error())
	}
	// Send a response back to the client
	conn.Write([]byte("Message received."))
	// Close the connection when you're done with it
	conn.Close()
}
868 chars
43 lines

This code listens for incoming connections on port 8080 and spawns a new goroutine to handle each incoming connection. The handleRequests function reads the incoming data, responds with an acknowledgement message, and closes the connection when it is done.

You can run this program by saving the code to a .go file and running it using the go run command in your terminal.

gistlibby LogSnag