Member-only story

Simplify Real-Time Messaging with Next.js and Go

Nemesis Blog
6 min readJan 5, 2025

Prerequisite

  1. NextJS 15 (Client)
  2. Go (Server)

Server (Go lang)

Installation

init new project with name chat-server and get package gorilla/websocket

mkdir chat-server
cd chat-server
go mod init github.com/<USERNAME_GITHUB>/chat-server
go get -u github.com/gorilla/websocket

Server Code

Create new file main.go and follow this code

package main

import (
"fmt"
"net/http"
"sync"
"time"

"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow all origins
},
}

// Client represents a connected user
type Client struct {
conn *websocket.Conn
room string
send chan Message
}

// Message represents a chat message
type Message struct {
Sender string `json:"sender"`
Text string `json:"text"`
Timestamp time.Time `json:"timestamp"`
Room string `json:"room"`
}

// Server manages connected clients and messages
type Server struct {
rooms map[string][]Message //…

--

--

No responses yet