├── Golang App
├── .env
├── utils
│ ├── cors.go
│ └── password-hash.go
├── go.mod
├── README.md
├── server.go
├── config
│ └── db.go
├── handlers
│ ├── hub.go
│ ├── response-handler.go
│ ├── structs.go
│ ├── socket-handler.go
│ ├── query-handlers.go
│ └── routes-handlers.go
├── constants
│ └── constant.go
├── routes.go
└── go.sum
├── React App
├── public
│ ├── robots.txt
│ ├── 404-page.png
│ ├── border.png
│ ├── favicon.ico
│ ├── loader.gif
│ ├── logo192.png
│ ├── logo512.png
│ ├── user-bg.png
│ ├── border-thick.png
│ ├── manifest.json
│ └── index.html
├── src
│ ├── setupTests.js
│ ├── App.test.js
│ ├── pages
│ │ ├── four-o-four
│ │ │ ├── four-o-four.js
│ │ │ └── four-o-four.css
│ │ ├── authentication
│ │ │ ├── authentication.css
│ │ │ ├── registration
│ │ │ │ ├── registration.css
│ │ │ │ └── registration.js
│ │ │ ├── login
│ │ │ │ ├── login.css
│ │ │ │ └── login.js
│ │ │ └── authentication.js
│ │ └── home
│ │ │ ├── chat-list
│ │ │ ├── chat-list.css
│ │ │ └── chat-list.js
│ │ │ ├── home.css
│ │ │ ├── conversation
│ │ │ ├── conversation.css
│ │ │ └── conversation.js
│ │ │ └── home.js
│ ├── services
│ │ ├── storage-service.js
│ │ ├── api-service.js
│ │ └── socket-service.js
│ ├── index.css
│ ├── index.js
│ ├── App.js
│ ├── App.css
│ ├── logo.svg
│ └── serviceWorker.js
├── .gitignore
├── package.json
└── README.md
├── .editorconfig
├── .gitignore
└── README.md
/Golang App/.env:
--------------------------------------------------------------------------------
1 | PORT=8000
2 | HOST=localhost
3 | DB_URL=mongodb://127.0.0.1:27017
4 | MONGODB_DATABASE=local
--------------------------------------------------------------------------------
/React App/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/React App/public/404-page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/404-page.png
--------------------------------------------------------------------------------
/React App/public/border.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/border.png
--------------------------------------------------------------------------------
/React App/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/favicon.ico
--------------------------------------------------------------------------------
/React App/public/loader.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/loader.gif
--------------------------------------------------------------------------------
/React App/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/logo192.png
--------------------------------------------------------------------------------
/React App/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/logo512.png
--------------------------------------------------------------------------------
/React App/public/user-bg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/user-bg.png
--------------------------------------------------------------------------------
/React App/public/border-thick.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/HEAD/React App/public/border-thick.png
--------------------------------------------------------------------------------
/React App/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/React App/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render();
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/React App/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/Golang App/utils/cors.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "github.com/rs/cors"
5 | )
6 |
7 | // GetCorsConfig will return the CORS values
8 | func GetCorsConfig() *cors.Cors {
9 | return cors.New(cors.Options{
10 | AllowedOrigins: []string{"*"}, // All origins
11 | AllowedMethods: []string{"GET", "POST", "OPTIONS", "DELETE", "PUT"}, // Allowing only get, just an example
12 | })
13 | }
14 |
--------------------------------------------------------------------------------
/Golang App/go.mod:
--------------------------------------------------------------------------------
1 | module private-chat
2 |
3 | go 1.13
4 |
5 | require (
6 | github.com/google/go-querystring v1.0.0 // indirect
7 | github.com/google/uuid v1.1.1
8 | github.com/gorilla/handlers v1.4.2
9 | github.com/gorilla/mux v1.7.4
10 | github.com/gorilla/websocket v1.4.2
11 | github.com/joho/godotenv v1.3.0
12 | github.com/rs/cors v1.7.0
13 | go.mongodb.org/mongo-driver v1.3.3
14 | golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
15 | )
16 |
--------------------------------------------------------------------------------
/Golang App/README.md:
--------------------------------------------------------------------------------
1 | # Real time private chat server built using Golang, MongoDB and WebSockets
2 |
3 | Real time private chat server built using Golang, MongoDB and WebSockets
4 |
5 | ## Installtion
6 |
7 | Below command will Install all the dependencies recursively.
8 |
9 | ```bash
10 | go get -d ./...
11 | ```
12 |
13 | ## Starting the GO server
14 |
15 | Use the below command to create executable and the run executable.
16 |
17 | ```bash
18 | go build
19 | ```
20 |
21 |
22 |
--------------------------------------------------------------------------------
/React App/src/pages/four-o-four/four-o-four.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import './four-o-four.css';
4 |
5 | function FourOFour() {
6 | return (
7 |
8 |
9 |
10 | What your looking for, it's not here.
11 |
12 |
13 |
Login again
14 |
15 | );
16 | }
17 |
18 | export default FourOFour;
--------------------------------------------------------------------------------
/React App/src/services/storage-service.js:
--------------------------------------------------------------------------------
1 | export function setItemInLS(key, value) {
2 | localStorage.setItem(
3 | key,
4 | JSON.stringify(value)
5 | )
6 | }
7 |
8 | export function getItemInLS(key) {
9 | const lSValue = localStorage.getItem(
10 | key,
11 | )
12 | if(lSValue) {
13 | return JSON.parse(lSValue)
14 | } else {
15 | return null;
16 | }
17 | }
18 |
19 | export function removeItemInLS(key) {
20 | localStorage.removeItem(
21 | key,
22 | )
23 | }
--------------------------------------------------------------------------------
/React App/src/index.css:
--------------------------------------------------------------------------------
1 | * {
2 | margin: 0;
3 | padding: 0;
4 | }
5 |
6 | body {
7 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
8 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
9 | sans-serif;
10 | -webkit-font-smoothing: antialiased;
11 | -moz-osx-font-smoothing: grayscale;
12 | }
13 |
14 | code {
15 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
16 | monospace;
17 | }
18 |
19 | .visibility-hidden {
20 | display: none !important;
21 | }
--------------------------------------------------------------------------------
/React App/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(
8 |
9 |
10 | ,
11 | document.getElementById('root')
12 | );
13 |
14 | // If you want your app to work offline and load faster, you can change
15 | // unregister() to register() below. Note this comes with some pitfalls.
16 | // Learn more about service workers: https://bit.ly/CRA-PWA
17 | serviceWorker.unregister();
18 |
--------------------------------------------------------------------------------
/React App/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/Golang App/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "os"
7 |
8 | "github.com/gorilla/mux"
9 | "github.com/joho/godotenv"
10 |
11 | config "private-chat/config"
12 | utils "private-chat/utils"
13 | )
14 |
15 | func main() {
16 |
17 | godotenv.Load()
18 |
19 | fmt.Println(
20 | fmt.Sprintf("%s%s%s%s", "Server will start at http://", os.Getenv("HOST"), ":", os.Getenv("PORT")),
21 | )
22 |
23 | config.ConnectDatabase()
24 |
25 | route := mux.NewRouter()
26 |
27 | AddApproutes(route)
28 |
29 | serverPath := ":" + os.Getenv("PORT")
30 |
31 | cors := utils.GetCorsConfig()
32 |
33 | http.ListenAndServe(serverPath, cors.Handler(route))
34 | }
35 |
--------------------------------------------------------------------------------
/React App/src/pages/four-o-four/four-o-four.css:
--------------------------------------------------------------------------------
1 | .app__FourOFour-container{
2 | text-align: center;
3 | }
4 |
5 | .app__FourOFour-box {
6 | background-image: url(/404-page.png);
7 | width: 80%;
8 | height: 300px;
9 | background-position: center;
10 | background-size: contain;
11 | margin: auto;
12 | text-align: center;
13 | margin-top: 10%;
14 | background-repeat: no-repeat;
15 | display: flex;
16 | flex-direction: column;
17 | justify-content: center;
18 | }
19 |
20 | .app__FourOFour-message {
21 | font-size: 50px;
22 | }
23 |
24 | .app__FourOFour-link {
25 | text-decoration: none;
26 | color: #000;
27 | font-size: 30px;;
28 | }
--------------------------------------------------------------------------------
/React App/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './App.css';
3 |
4 |
5 | import {
6 | BrowserRouter as Router,
7 | Route,
8 | Switch
9 | } from "react-router-dom";
10 |
11 | import Authentication from './pages/authentication/authentication';
12 | import Home from './pages/home/home';
13 | import FourOFour from './pages/four-o-four/four-o-four';
14 |
15 |
16 | function App() {
17 | return (
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | );
26 | }
27 |
28 | export default App;
29 |
--------------------------------------------------------------------------------
/React App/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Golang App/utils/password-hash.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "errors"
5 |
6 | "golang.org/x/crypto/bcrypt"
7 | )
8 |
9 | // CreatePassword will create password using bcrypt
10 | func CreatePassword(passwordString string) (string, error) {
11 | hashedPassword, err := bcrypt.GenerateFromPassword([]byte(passwordString), 8)
12 | if err != nil {
13 | return "", errors.New("Error occurred while creating a Hash")
14 | }
15 |
16 | return string(hashedPassword), nil
17 | }
18 |
19 | // ComparePasswords will create password using bcrypt
20 | func ComparePasswords(password string, hashedPassword string) error {
21 | err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
22 | if err != nil {
23 | return errors.New("The '" + password + "' and '" + hashedPassword + "' strings don't match")
24 | }
25 | return nil
26 | }
27 |
--------------------------------------------------------------------------------
/Golang App/config/db.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "context"
5 | "log"
6 | "os"
7 |
8 | "go.mongodb.org/mongo-driver/mongo"
9 | "go.mongodb.org/mongo-driver/mongo/options"
10 | )
11 |
12 | // MongoDBClient is exported Mongo Database client
13 | var MongoDBClient *mongo.Client
14 |
15 | // ConnectDatabase is used to connect the MongoDB database
16 | func ConnectDatabase() {
17 | log.Println("Database connecting...")
18 | // Set client options
19 | clientOptions := options.Client().ApplyURI(os.Getenv("DB_URL"))
20 |
21 | // Connect to MongoDB
22 | client, err := mongo.Connect(context.TODO(), clientOptions)
23 | MongoDBClient = client
24 | if err != nil {
25 | log.Fatal(err)
26 | }
27 |
28 | // Check the connection
29 | err = MongoDBClient.Ping(context.TODO(), nil)
30 |
31 | if err != nil {
32 | log.Fatal(err)
33 | }
34 |
35 | log.Println("Database Connected.")
36 | }
37 |
--------------------------------------------------------------------------------
/Golang App/handlers/hub.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | // Hub maintains the set of active clients and broadcasts messages to the clients.
4 | type Hub struct {
5 | // Registered clients.
6 | clients map[*Client]bool
7 |
8 | // Register requests from the clients.
9 | register chan *Client
10 |
11 | // Unregister requests from clients.
12 | unregister chan *Client
13 | }
14 |
15 | // NewHub will will give an instance of an Hub
16 | func NewHub() *Hub {
17 | return &Hub{
18 | register: make(chan *Client),
19 | unregister: make(chan *Client),
20 | clients: make(map[*Client]bool),
21 | }
22 | }
23 |
24 | // Run will execute Go Routines to check incoming Socket events
25 | func (hub *Hub) Run() {
26 | for {
27 | select {
28 | case client := <-hub.register:
29 | HandleUserRegisterEvent(hub, client)
30 |
31 | case client := <-hub.unregister:
32 | HandleUserDisconnectEvent(hub, client)
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/React App/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "private-chat-app-golang",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "react": "^16.13.1",
10 | "react-debounce-input": "^3.2.2",
11 | "react-dom": "^16.13.1",
12 | "react-router-dom": "^5.2.0",
13 | "react-scripts": "3.4.1",
14 | "socket.io-client": "^2.3.0"
15 | },
16 | "scripts": {
17 | "start": "react-scripts start",
18 | "build": "react-scripts build",
19 | "test": "react-scripts test",
20 | "eject": "react-scripts eject"
21 | },
22 | "eslintConfig": {
23 | "extends": "react-app"
24 | },
25 | "browserslist": {
26 | "production": [
27 | ">0.2%",
28 | "not dead",
29 | "not op_mini all"
30 | ],
31 | "development": [
32 | "last 1 chrome version",
33 | "last 1 firefox version",
34 | "last 1 safari version"
35 | ]
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Golang App/constants/constant.go:
--------------------------------------------------------------------------------
1 | package constants
2 |
3 | // Constant will export all application Constants
4 | const (
5 | // Request Paramyter Validation error/success messages
6 | UsernameCantBeEmpty = "Username can't be empty."
7 | UsernameIsAvailable = "Username is available."
8 | UsernameIsNotAvailable = "Username is not available."
9 | PasswordCantBeEmpty = "Password can't be empty."
10 | UsernameAndPasswordCantBeEmpty = "Username and Password can't be empty."
11 | LoginPasswordIsInCorrect = "Your Login Password is incorrect."
12 | UserRegistrationCompleted = "User Registration Completed."
13 | UserLoginCompleted = "User Login is Completed."
14 | YouAreNotLoggedIN = "You are not logged in."
15 | YouAreLoggedIN = "You are logged in."
16 | UserIsNotRegisteredWithUs = "This account does not exist in our system."
17 |
18 | // Application response messages
19 | SuccessfulResponse = "Request completed successfully"
20 | ServerFailedResponse = "Request failed to complete, we are working on it"
21 | APIWelcomeMessage = "This is an API for Realtime Private chat application build in GoLang"
22 | )
23 |
--------------------------------------------------------------------------------
/React App/src/pages/authentication/authentication.css:
--------------------------------------------------------------------------------
1 | .app__loader {
2 | position: absolute;
3 | height: 100%;
4 | width: 100%;
5 | background: rgba(255, 255, 255, 0.9);
6 | z-index: 1;
7 | flex-direction: column;
8 | justify-content: center;
9 | display: none;
10 | }
11 |
12 | .app__loader img {
13 | width: 60px;
14 | height: 60px;
15 | margin: auto;
16 | }
17 |
18 | .app__loader.active {
19 | display: flex;
20 | }
21 |
22 | .app__authentication-container {
23 | width: 450px;
24 | margin: 0 auto;
25 | }
26 |
27 | .authentication__tab-switcher {
28 | width: 100%;
29 | text-align: center;
30 | }
31 |
32 | .authentication__tab-viewer {
33 | width: 100%;
34 | }
35 |
36 | button.authentication__tab-button {
37 | width: 30%;
38 | background: #fff;
39 | border: 0px;
40 | padding: 7px;
41 | margin-bottom: 20px;
42 | font-size: 20px;
43 | cursor: pointer;
44 | outline: none;
45 | position: relative;
46 | }
47 |
48 | button.active.authentication__tab-button::after {
49 | content: '';
50 | background: url(/border.png);
51 | height: 11px;
52 | width: 50px;
53 | position: absolute;
54 | bottom: 0;
55 | left: 30%;
56 | background-size: inherit;
57 | }
--------------------------------------------------------------------------------
/React App/src/pages/authentication/registration/registration.css:
--------------------------------------------------------------------------------
1 | .app__register-container {
2 | width: 100%;
3 | }
4 |
5 | .app__form-row {
6 | width: 100%;
7 | margin-bottom: 15px;
8 | }
9 |
10 | .app__form-row label{
11 | display: block;
12 | }
13 |
14 | .app__form-row input{
15 | width: 100%;
16 | font-size: 18px;
17 | padding: 4px 2px;
18 | outline: none;
19 | border: 2px solid transparent;
20 | -webkit-border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
21 | /* Safari 3.1-5 */
22 | -o-border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
23 | /* Opera 11-12.1 */
24 | border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
25 | }
26 |
27 | .app__form-row button {
28 | background-color: rgba(127, 255, 212, 0.33);
29 | padding: 5px 10px;
30 | font-size: 19px;
31 | outline: none;
32 | cursor: pointer;
33 | border: 2px solid transparent;
34 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
35 | /* Safari 3.1-5 */
36 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
37 | /* Opera 11-12.1 */
38 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
39 | }
--------------------------------------------------------------------------------
/React App/src/pages/authentication/login/login.css:
--------------------------------------------------------------------------------
1 | .app__login-container {
2 | width: 100%;;
3 | }
4 |
5 | .app__form-row {
6 | width: 100%;
7 | margin-bottom: 15px;
8 | }
9 |
10 | .app__form-row label{
11 | display: block;
12 | }
13 |
14 | .app__form-row input{
15 | width: 100%;
16 | font-size: 18px;
17 | padding: 4px 2px;
18 | outline: none;
19 | border: 2px solid transparent;
20 | -webkit-border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
21 | /* Safari 3.1-5 */
22 | -o-border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
23 | /* Opera 11-12.1 */
24 | border-image: url('/border.png') 10 / 10px 5px 5px 5px / 10px 5px 5px 10px round;
25 | }
26 |
27 | .app__form-row button {
28 | background-color: rgba(127, 255, 212, 0.33);
29 | padding: 5px 10px;
30 | font-size: 19px;
31 | outline: none;
32 | cursor: pointer;
33 | border: 2px solid transparent;
34 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
35 | /* Safari 3.1-5 */
36 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
37 | /* Opera 11-12.1 */
38 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
39 | }
40 |
41 | .error-message {
42 | color: red;;
43 | }
--------------------------------------------------------------------------------
/React App/src/pages/home/chat-list/chat-list.css:
--------------------------------------------------------------------------------
1 | .app__chatlist-container {
2 | width: 250px;
3 | margin: auto;
4 | }
5 |
6 | .user__chat-list {
7 | width: 100%;
8 | }
9 |
10 | .user-name {
11 | width: 100%;
12 | font-size: 18px;
13 | padding: 10px 5px;
14 | outline: none;
15 | margin-bottom: 20px;
16 | cursor: pointer;
17 | background-color: rgba(127, 255, 212, 0.33);
18 | border: 2px solid transparent;
19 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
20 | /* Safari 3.1-5 */
21 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
22 | /* Opera 11-12.1 */
23 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
24 | }
25 |
26 | .selected-username {
27 | background: url('/user-bg.png') -12px 55px;
28 | }
29 |
30 | .online {
31 | height: 15px;
32 | width: 15px;
33 | border-radius: 10px;
34 | background-color: rgb(0, 255, 42);
35 | float: right;
36 | margin-top: 0.5vh;
37 | margin-right: 10px;
38 | box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.567)
39 | }
40 |
41 | .offline {
42 | height: 15px;
43 | width: 15px;
44 | border-radius: 10px;
45 | background-color: rgb(255, 0, 0);
46 | float: right;
47 | margin-top: 0.5vh;
48 | margin-right: 10px;
49 | box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.567)
50 | }
--------------------------------------------------------------------------------
/Golang App/routes.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "net/http"
6 |
7 | "github.com/gorilla/mux"
8 | "github.com/gorilla/websocket"
9 |
10 | handlers "private-chat/handlers"
11 | )
12 |
13 | // AddApproutes will add the routes for the application
14 | func AddApproutes(route *mux.Router) {
15 |
16 | log.Println("Loadeding Routes...")
17 |
18 | hub := handlers.NewHub()
19 | go hub.Run()
20 |
21 | route.HandleFunc("/", handlers.RenderHome)
22 |
23 | route.HandleFunc("/isUsernameAvailable/{username}", handlers.IsUsernameAvailable)
24 |
25 | route.HandleFunc("/login", handlers.Login).Methods("POST")
26 |
27 | route.HandleFunc("/registration", handlers.Registertation).Methods("POST")
28 |
29 | route.HandleFunc("/userSessionCheck/{userID}", handlers.UserSessionCheck)
30 |
31 | route.HandleFunc("/getConversation/{toUserID}/{fromUserID}", handlers.GetMessagesHandler)
32 |
33 | route.HandleFunc("/ws/{userID}", func(responseWriter http.ResponseWriter, request *http.Request) {
34 | var upgrader = websocket.Upgrader{
35 | ReadBufferSize: 1024,
36 | WriteBufferSize: 1024,
37 | }
38 |
39 | // Reading username from request parameter
40 | userID := mux.Vars(request)["userID"]
41 |
42 | // Upgrading the HTTP connection socket connection
43 | upgrader.CheckOrigin = func(r *http.Request) bool { return true }
44 |
45 | connection, err := upgrader.Upgrade(responseWriter, request, nil)
46 | if err != nil {
47 | log.Println(err)
48 | return
49 | }
50 |
51 | handlers.CreateNewSocketUser(hub, connection, userID)
52 |
53 | })
54 |
55 | log.Println("Routes are Loaded.")
56 | }
57 |
--------------------------------------------------------------------------------
/Golang App/handlers/response-handler.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "encoding/json"
5 | "net/http"
6 |
7 | constants "private-chat/constants"
8 | )
9 |
10 | // APIResponseStruct is universal API template for sending API Response
11 | type APIResponseStruct struct {
12 | Code int `json:"code"`
13 | Status string `json:"status"`
14 | Message string `json:"message"`
15 | Response interface{} `json:"response"`
16 | }
17 |
18 | // ReturnResponse will be used as Response template to send the response for API
19 | func ReturnResponse(response http.ResponseWriter, request *http.Request, apiResponse APIResponseStruct) {
20 | var (
21 | responseMessage, responseStatusText string
22 | responseHTTPCode int
23 | )
24 |
25 | if apiResponse.Code == 0 {
26 | responseHTTPCode = http.StatusOK
27 | } else {
28 | responseHTTPCode = apiResponse.Code
29 | }
30 |
31 | if apiResponse.Status != "" {
32 | responseStatusText = apiResponse.Status
33 | } else {
34 | responseStatusText = http.StatusText(http.StatusOK)
35 | }
36 |
37 | if apiResponse.Message != "" {
38 | responseMessage = apiResponse.Message
39 | } else {
40 | responseMessage = constants.SuccessfulResponse
41 | }
42 |
43 | httpResponse := &APIResponseStruct{
44 | Code: responseHTTPCode,
45 | Status: responseStatusText,
46 | Message: responseMessage,
47 | Response: apiResponse.Response,
48 | }
49 | jsonResponse, err := json.Marshal(httpResponse)
50 | if err != nil {
51 | panic(err)
52 | }
53 | response.Header().Set("Content-Type", "application/json")
54 | response.WriteHeader(httpResponse.Code)
55 | response.Write(jsonResponse)
56 | }
57 |
--------------------------------------------------------------------------------
/React App/src/pages/authentication/authentication.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 |
3 | import './authentication.css';
4 |
5 | import Login from './login/login';
6 | import Registration from './registration/registration'
7 |
8 | function Authentication() {
9 |
10 | const [activeTab, setTabType] = useState('login');
11 | const [loaderStatus, setLoaderStatus] = useState(false);
12 |
13 | const changeTabType = (type) => {
14 | setTabType(type);
15 | }
16 |
17 | const getActiveClass = (type) => {
18 | return type === activeTab ? 'active' : '';
19 | };
20 |
21 | const displayPageLoader = (shouldDisplay) => {
22 | setLoaderStatus(shouldDisplay)
23 | }
24 |
25 | return (
26 |
27 |
28 |

29 |
30 |
31 |
32 |
38 |
44 |
45 |
46 | {activeTab === 'login' ? : }
47 |
48 |
49 |
50 | );
51 | }
52 |
53 | export default Authentication;
--------------------------------------------------------------------------------
/Golang App/handlers/structs.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import "github.com/gorilla/websocket"
4 |
5 | // UserDetailsStruct is a universal struct for mapping the user details
6 | type UserDetailsStruct struct {
7 | ID string `bson:"_id,omitempty"`
8 | Username string
9 | Password string
10 | Online string
11 | SocketID string
12 | }
13 |
14 | // ConversationStruct is a universal struct for mapping the conversations
15 | type ConversationStruct struct {
16 | ID string `json:"id" bson:"_id,omitempty"`
17 | Message string `json:"message"`
18 | ToUserID string `json:"toUserID"`
19 | FromUserID string `json:"fromUserID"`
20 | }
21 |
22 | // UserDetailsRequestPayloadStruct represents payload for Login and Registration request
23 | type UserDetailsRequestPayloadStruct struct {
24 | Username string
25 | Password string
26 | }
27 |
28 | // UserDetailsResponsePayloadStruct represents payload for Login and Registration response
29 | type UserDetailsResponsePayloadStruct struct {
30 | Username string `json:"username"`
31 | UserID string `json:"userID"`
32 | Online string `json:"online"`
33 | }
34 |
35 | // SocketEventStruct struct of socket events
36 | type SocketEventStruct struct {
37 | EventName string `json:"eventName"`
38 | EventPayload interface{} `json:"eventPayload"`
39 | }
40 |
41 | // Client is a middleman between the websocket connection and the hub.
42 | type Client struct {
43 | hub *Hub
44 | webSocketConnection *websocket.Conn
45 | send chan SocketEventStruct
46 | userID string
47 | }
48 |
49 | // MessagePayloadStruct is a struct used for message Payload
50 | type MessagePayloadStruct struct {
51 | FromUserID string `json:"fromUserID"`
52 | ToUserID string `json:"toUserID"`
53 | Message string `json:"message"`
54 | }
55 |
--------------------------------------------------------------------------------
/React App/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/React App/src/services/api-service.js:
--------------------------------------------------------------------------------
1 | const API_ENDPOINTS = "http://127.0.0.1:8000";
2 |
3 | export async function loginHTTPRequest(username, password) {
4 | const response = await fetch(`${API_ENDPOINTS}/login`, {
5 | method: 'POST',
6 | headers: {
7 | 'Content-Type': 'application/json'
8 | },
9 | body: JSON.stringify({
10 | username,
11 | password
12 | })
13 | });
14 | return await response.json();
15 | }
16 | export async function registerHTTPRequest(username, password) {
17 | const response = await fetch(`${API_ENDPOINTS}/registration`, {
18 | method: 'POST',
19 | headers: {
20 | 'Content-Type': 'application/json'
21 | },
22 | body: JSON.stringify({
23 | username,
24 | password
25 | })
26 | });
27 | return await response.json();
28 | }
29 |
30 | export async function isUsernameAvailableHTTPRequest(username) {
31 | const response = await fetch(`${API_ENDPOINTS}/isUsernameAvailable/${username}`, {
32 | method: 'GET',
33 | headers: {
34 | 'Content-Type': 'application/json'
35 | }
36 | });
37 | return await response.json();
38 | }
39 |
40 | export async function userSessionCheckHTTPRequest(username) {
41 | const response = await fetch(`${API_ENDPOINTS}/userSessionCheck/${username}`, {
42 | method: 'GET',
43 | headers: {
44 | 'Content-Type': 'application/json'
45 | }
46 | });
47 | return await response.json();
48 | }
49 |
50 |
51 | export async function getConversationBetweenUsers(toUserID, fromUserID) {
52 | const response = await fetch(`${API_ENDPOINTS}/getConversation/${toUserID}/${fromUserID}`, {
53 | method: 'GET',
54 | headers: {
55 | 'Content-Type': 'application/json'
56 | }
57 | });
58 | return await response.json();
59 | }
60 |
--------------------------------------------------------------------------------
/React App/src/pages/authentication/login/login.js:
--------------------------------------------------------------------------------
1 | import React, {useState} from 'react';
2 | import { withRouter } from 'react-router-dom';
3 |
4 | import { loginHTTPRequest } from "./../../../services/api-service";
5 | import { setItemInLS } from "./../../../services/storage-service";
6 |
7 | import './login.css'
8 |
9 | function Login(props) {
10 |
11 | const [loginErrorMessage, setErrorMessage] = useState(null);
12 | const [username, updateUsername] = useState(null);
13 | const [password, updatePassword] = useState(null);
14 |
15 |
16 | const handleUsernameChange = (event) => {
17 | updateUsername(event.target.value)
18 | }
19 |
20 | const handlePasswordChange = (event) => {
21 | updatePassword(event.target.value)
22 | }
23 |
24 | const loginUser = async () => {
25 | props.displayPageLoader(true);
26 | const userDetails = await loginHTTPRequest(username, password);
27 | props.displayPageLoader(false);
28 |
29 | if (userDetails.code === 200) {
30 | setItemInLS('userDetails', userDetails.response)
31 | props.history.push(`/home`)
32 | } else {
33 | setErrorMessage(userDetails.message);
34 | }
35 | };
36 |
37 | return (
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | {loginErrorMessage? loginErrorMessage : ''}
49 |
50 |
51 |
52 |
53 |
54 | );
55 | }
56 |
57 | export default withRouter(Login);
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Real time private chatting app using React, Golang and mongodb
2 |
3 | As the title reads, This app is private chat application built using React (version 16.13.1). This react application is built using functional components only, so You won't find `setState`. Here I have React Hooks to update the components and for React life cycles.
4 | Server-side is written in Golang (version 1.13.8) and MongoDB(version 3.6.3).
5 |
6 | This project was generated with [create-react-app](https://github.com/facebook/create-react-app) version 2.1.8.
7 |
8 | ## React Code
9 | Code for React application is in [React folder](https://github.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/tree/master/React%20App).
10 |
11 | ## GoLang API Code
12 | Code for GoLang application is in [GoLang API folder](https://github.com/ShankyTiwari/Real-time-private-chatting-app-using-React-Golang-and-mongodb/tree/master/Golang%20App).
13 |
14 |
15 | ## Explanation and Blog Post
16 | Coming Soon.
17 |
18 |
19 | # Looking for Class based React chat
20 | I have written this application in Class based React as well, [Read this popular Blog post](https://www.codershood.info/2019/03/31/real-time-private-chatting-app-using-react-nodejs-mongodb-and-socket-io-part-1/).
21 |
22 |
23 | # Looking for Angular 2 and above
24 | I have written this application in Angular as well, [Read this popular Blog post](http://www.codershood.info/2017/02/09/real-time-private-chatting-app-using-angular-2-nodejs-mongodb-socket-io-part-1/).
25 | Alternatively, you can download an **[Ebook](http://www.codershood.info)** for the same application, along with Ebook you will get the source code of the application. In the ebook, you will get some of the must-have features such as notifications and online/offline chat list.
26 |
27 | # Looking for Plain Old AngularJS
28 | I have written this application in AngularJs as well, [Read this popular Blog post](http://www.codershood.info/2015/12/10/real-time-chatting-app-using-nodejs-mysql-angularjs-and-socket-io-part-1/).
29 |
--------------------------------------------------------------------------------
/React App/src/pages/home/home.css:
--------------------------------------------------------------------------------
1 | .app__home-container {
2 | display: flex;
3 | width: 60%;
4 | margin: auto;
5 | flex-direction: column;;
6 | }
7 |
8 | .app__header-container {
9 | display: flex;
10 | justify-content: space-between;
11 | padding-bottom: 20px;
12 | margin-bottom: 50px;
13 | margin-top: 20px;
14 | border-bottom: 2px solid transparent;
15 |
16 | -webkit-border-image: url('/border.png') 10 / 0px 0px 10px 0px / 0px 0px 10px 0px round;
17 | /* Safari 3.1-5 */
18 | -o-border-image: url('/border.png') 10 / 0px 0px 10px 0px / 0px 0px 10px 0px round;
19 | /* Opera 11-12.1 */
20 | border-image: url('/border.png') 10 / 0px 0px 10px 0px / 0px 0px 10px 0px round;
21 | }
22 |
23 | .app__header-user {
24 | display: flex;
25 | }
26 |
27 | .username-initial {
28 | width: 45px;
29 | height: 45px;
30 | background: aquamarine;
31 | border-radius: 50%;
32 | text-align: center;
33 | font-size: 30px;
34 | margin-right: 10px;
35 | border: 2px solid transparent;
36 | -webkit-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
37 | /* Safari 3.1-5 */
38 | -o-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
39 | /* Opera 11-12.1 */
40 | border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
41 | }
42 |
43 | .user-details {
44 | display: flex;
45 | justify-content: center;
46 | flex-direction: column;
47 | text-transform: capitalize;
48 | }
49 |
50 | .logout {
51 | background: #fff;
52 | padding: 2.5px 5px;
53 | font-size: 15px;
54 | outline: none;
55 | cursor: pointer;
56 | border: 2px solid transparent;
57 | -webkit-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
58 | /* Safari 3.1-5 */
59 | -o-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
60 | /* Opera 11-12.1 */
61 | border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
62 | }
63 |
64 | .app__content-container {
65 | display: flex;
66 | width: 100%;
67 | }
68 | .app__home-chatlist {
69 | flex: 1;
70 | margin-right: 30px;
71 | }
72 |
73 | .app__home-message {
74 | flex: 2;
75 | }
--------------------------------------------------------------------------------
/React App/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/React App/src/pages/home/chat-list/chat-list.js:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from 'react';
2 |
3 | import {
4 | eventEmitter
5 | } from "./../../../services/socket-service";
6 |
7 | import './chat-list.css'
8 |
9 | function ChatList(props) {
10 | const [selectedUser, updateSelectedUser] = useState(null);
11 | const [chatList, setChatList] = useState([]);
12 |
13 | const chatListSubscription = (socketPayload) => {
14 | let newChatList = chatList;
15 |
16 | if (socketPayload.type === 'new-user-joined') {
17 | const incomingChatList = socketPayload.chatlist;
18 | if (incomingChatList) {
19 | newChatList = newChatList.filter(
20 | (obj) => obj.userID !== incomingChatList.userID
21 | );
22 | }
23 |
24 | /* Adding new online user into chat list array */
25 | newChatList = [...newChatList, ...[incomingChatList]];
26 | } else if (socketPayload.type === 'user-disconnected') {
27 | const outGoingUser = socketPayload.chatlist;
28 | const loggedOutUserIndex = newChatList.findIndex(
29 | (obj) => obj.userID === outGoingUser.userID
30 | );
31 | if (loggedOutUserIndex >= 0) {
32 | newChatList[loggedOutUserIndex].online = 'N';
33 | }
34 | } else {
35 | newChatList = socketPayload.chatlist;
36 | }
37 |
38 | // slice is used to create aa new instance of an array
39 | setChatList(newChatList.slice());
40 | };
41 |
42 | useEffect(() => {
43 | eventEmitter.on('chatlist-response', chatListSubscription);
44 | return () => {
45 | eventEmitter.removeListener('chatlist-response', chatListSubscription);
46 | };
47 | });
48 |
49 | const setSelectedUser = (user) => {
50 | if (user) {
51 | updateSelectedUser(user);
52 | props.updateSelectedUser(user);
53 | }
54 | };
55 |
56 | if(chatList && chatList.length === 0) {
57 | return (
58 |
59 | {chatList.length === 0 ? 'Loading your chat list.' : 'No User Available to chat.'}
60 |
61 | );
62 | }
63 |
64 | return (
65 |
66 |
67 | {chatList.map((user, index) => (
68 |
setSelectedUser(user)}
76 | >
77 | {user.username}
78 |
79 |
80 | ))}
81 |
82 |
83 | );
84 | }
85 |
86 | export default ChatList;
--------------------------------------------------------------------------------
/React App/src/pages/authentication/registration/registration.js:
--------------------------------------------------------------------------------
1 | import React, {useState} from 'react';
2 | import { withRouter } from 'react-router-dom';
3 |
4 | import { isUsernameAvailableHTTPRequest, registerHTTPRequest } from "./../../../services/api-service";
5 | import { setItemInLS } from "./../../../services/storage-service";
6 |
7 | import './registration.css'
8 |
9 | function Registration(props) {
10 | const [registrationErrorMessage, setErrorMessage] = useState(null);
11 | const [username, updateUsername] = useState(null);
12 | const [password, updatePassword] = useState(null);
13 |
14 | let typingTimer = null;
15 |
16 |
17 | const handlePasswordChange = async (event) => {
18 | updatePassword(event.target.value);
19 | }
20 |
21 | const handleKeyDownChange = (event) => {
22 | clearTimeout(typingTimer);
23 | }
24 |
25 | const handleKeyUpChange = (event) => {
26 | const username = event.target.value;
27 | typingTimer = setTimeout( () => {
28 | checkIfUsernameAvailable(username);
29 | }, 1200);
30 | }
31 |
32 | const checkIfUsernameAvailable = async (username) => {
33 | props.displayPageLoader(true);
34 | const isUsernameAvailableResponse = await isUsernameAvailableHTTPRequest(username);
35 | props.displayPageLoader(false);
36 | if (!isUsernameAvailableResponse.response.isUsernameAvailable) {
37 | setErrorMessage(isUsernameAvailableResponse.message);
38 | } else {
39 | setErrorMessage(null);
40 | }
41 | updateUsername(username);
42 | }
43 |
44 | const registerUser = async () => {
45 | props.displayPageLoader(true);
46 | const userDetails = await registerHTTPRequest(username, password);
47 | props.displayPageLoader(false);
48 |
49 | if (userDetails.code === 200) {
50 | setItemInLS('userDetails', userDetails.response)
51 | props.history.push(`/home`)
52 | } else {
53 | setErrorMessage(userDetails.message);
54 | }
55 | };
56 |
57 | return (
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | {registrationErrorMessage? registrationErrorMessage : ''}
69 |
70 |
71 |
72 |
73 |
74 | );
75 | }
76 |
77 | export default withRouter(Registration);
--------------------------------------------------------------------------------
/React App/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `yarn start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `yarn test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `yarn build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `yarn eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `yarn build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/React App/src/pages/home/conversation/conversation.css:
--------------------------------------------------------------------------------
1 | .app__conversion-container {
2 | width: 100%;;
3 | }
4 |
5 |
6 | .message-overlay {
7 | height: 400px;
8 | display: flex;
9 | text-align: center;
10 | justify-content: center;
11 | flex-direction: column;
12 | border: 2px solid transparent;
13 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
14 | /* Safari 3.1-5 */
15 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
16 | /* Opera 11-12.1 */
17 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
18 | }
19 |
20 |
21 | .start-chatting-banner {
22 | display: flex;
23 | text-align: center;
24 | justify-content: center;
25 | flex-direction: column;
26 | }
27 |
28 | .sub-heading {
29 | font-size: 20px;
30 | color: rgba(0, 123, 255);
31 | }
32 |
33 |
34 | .message-thread-container {
35 | height: 400px;
36 | overflow-y: scroll;
37 | list-style-type: none;
38 | width: 100%;
39 | border: solid 1px #BDBDBD;
40 | margin: 0px;
41 | padding-bottom: 10px;
42 | padding-left: 0px;
43 | border: 2px solid transparent;
44 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
45 | /* Safari 3.1-5 */
46 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
47 | /* Opera 11-12.1 */
48 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
49 | }
50 |
51 | .message-thread-container .message {
52 | clear: both;
53 | text-decoration: none;
54 | list-style-type: none;
55 | margin: 20px 10px 0px 20px;
56 | float: left;
57 | margin-right: 20px;
58 | padding: 25px 34px;
59 | min-width: 160px;
60 | min-height: 10px;
61 | max-width: 350px;
62 | line-height: 1.4;
63 | word-wrap: break-word;
64 | color: #444444;
65 | text-align: left;
66 | background-color: rgba(127, 255, 212, 0.33);
67 | border: 2px solid transparent;
68 | -webkit-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
69 | /* Safari 3.1-5 */
70 | -o-border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
71 | /* Opera 11-12.1 */
72 | border-image: url('/border.png') 10 / 10px 10px 10px 10px / 5px 5px 5px 5px round;
73 |
74 | }
75 |
76 | .align-right {
77 | float: right !important;
78 | text-align: right;
79 | }
80 |
81 |
82 | .app__message-container .message {
83 | width: 200px;
84 | font-size: 18px;
85 | padding: 4px 2px;
86 | outline: none;
87 | margin-bottom: 20px;
88 | }
89 |
90 | .app__text-container .text-type {
91 | width: 99%;
92 | font-size: 18px;
93 | outline: none;
94 | margin-bottom: 20px;
95 | border: 2px solid transparent;
96 | -webkit-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 10px 15px 5px 10px round;
97 | -o-border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 10px 15px 5px 10px round;
98 | border-image: url('/border-thick.png') 10 / 10px 10px 10px 10px / 10px 15px 5px 10px round;
99 | }
--------------------------------------------------------------------------------
/React App/src/services/socket-service.js:
--------------------------------------------------------------------------------
1 | const events = require('events');
2 |
3 | const CHAT_SERVER_ENDPOINT = "127.0.0.1:8000";
4 | let webSocketConnection = null;
5 |
6 | export const eventEmitter = new events.EventEmitter();
7 |
8 | export function connectToWebSocket(userID) {
9 | if (userID === "" && userID === null && userID === undefined) {
10 | return {
11 | message: "You need User ID to connect to the Chat server",
12 | webSocketConnection: null
13 | }
14 | } else if (!window["WebSocket"]) {
15 | return {
16 | message: "Your Browser doesn't support Web Sockets",
17 | webSocketConnection: null
18 | }
19 | }
20 | if (window["WebSocket"]) {
21 | webSocketConnection = new WebSocket("ws://" + CHAT_SERVER_ENDPOINT + "/ws/" + userID);
22 | return {
23 | message: "You are connected to Chat Server",
24 | webSocketConnection
25 | }
26 | }
27 | }
28 |
29 | export function sendWebSocketMessage(messagePayload) {
30 | if (webSocketConnection === null) {
31 | return;
32 | }
33 | webSocketConnection.send(
34 | JSON.stringify({
35 | eventName: 'message',
36 | eventPayload: messagePayload
37 | })
38 | );
39 | }
40 |
41 | export function emitLogoutEvent(userID) {
42 | if (webSocketConnection === null) {
43 | return;
44 | }
45 | webSocketConnection.close();
46 | }
47 |
48 | export function listenToWebSocketEvents() {
49 |
50 | if (webSocketConnection === null) {
51 | return;
52 | }
53 |
54 | webSocketConnection.onclose = (event) => {
55 | eventEmitter.emit('disconnect', event);
56 | };
57 |
58 | webSocketConnection.onmessage = (event) => {
59 | try {
60 | const socketPayload = JSON.parse(event.data);
61 | switch (socketPayload.eventName) {
62 | case 'chatlist-response':
63 | if (!socketPayload.eventPayload) {
64 | return
65 | }
66 | eventEmitter.emit(
67 | 'chatlist-response',
68 | socketPayload.eventPayload
69 | );
70 |
71 | break;
72 |
73 | case 'disconnect':
74 | if (!socketPayload.eventPayload) {
75 | return
76 | }
77 | eventEmitter.emit(
78 | 'chatlist-response',
79 | socketPayload.eventPayload
80 | );
81 |
82 | break;
83 |
84 | case 'message-response':
85 |
86 | if (!socketPayload.eventPayload) {
87 | return
88 | }
89 |
90 | eventEmitter.emit('message-response', socketPayload.eventPayload);
91 | break;
92 |
93 | default:
94 | break;
95 | }
96 | } catch (error) {
97 | console.log(error)
98 | console.warn('Something went wrong while decoding the Message Payload')
99 | }
100 | };
101 | }
--------------------------------------------------------------------------------
/React App/src/pages/home/home.js:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from 'react';
2 | import { withRouter } from 'react-router-dom';
3 |
4 | import { userSessionCheckHTTPRequest } from "./../../services/api-service";
5 | import {
6 | connectToWebSocket,
7 | listenToWebSocketEvents,
8 | emitLogoutEvent,
9 | } from './../../services/socket-service';
10 | import {
11 | getItemInLS,
12 | removeItemInLS
13 | } from "./../../services/storage-service";
14 |
15 | import ChatList from './chat-list/chat-list';
16 | import Conversation from './conversation/conversation';
17 |
18 | import './home.css';
19 |
20 | const useFetch = (props) => {
21 |
22 | const [internalError, setInternalError] = useState(null);
23 | const userDetails = getItemInLS('userDetails');
24 |
25 | useEffect(() => {
26 |
27 | (async () => {
28 | if (userDetails === null || userDetails === '') {
29 | props.history.push(`/`);
30 | } else {
31 | const isUserLoggedInResponse = await userSessionCheckHTTPRequest(
32 | userDetails.userID
33 | );
34 | if (!isUserLoggedInResponse.response) {
35 | props.history.push(`/`);
36 | } else {
37 | const webSocketConnection = connectToWebSocket(userDetails.userID);
38 | if (webSocketConnection.webSocketConnection === null) {
39 | setInternalError(webSocketConnection.message);
40 | } else {
41 | listenToWebSocketEvents()
42 | }
43 | }
44 | }
45 | })();
46 |
47 | }, [props, userDetails]);
48 | return [userDetails, internalError];
49 | };
50 |
51 | const getUserNameInitial = (userDetails) => {
52 | if(userDetails && userDetails.username) {
53 | return userDetails.username[0]
54 | }
55 | return '_';
56 | }
57 |
58 |
59 | const getUserName = (userDetails) => {
60 | if (userDetails && userDetails.username) {
61 | return userDetails.username;
62 | }
63 | return '___';
64 | };
65 |
66 | const logoutUser = (props, userDetails) => {
67 | if (userDetails.userID) {
68 | removeItemInLS('userDetails');
69 | emitLogoutEvent(userDetails.userID);
70 | props.history.push(`/`);
71 | }
72 | };
73 |
74 |
75 |
76 | function Home(props) {
77 | const [userDetails, internalError] = useFetch(props);
78 | const [selectedUser, updateSelectedUser] = useState(null);
79 |
80 | if (internalError !== null) {
81 | return {internalError}
;
82 | }
83 |
84 | return (
85 |
86 |
101 |
102 |
103 | {
105 | updateSelectedUser(user);
106 | }}
107 | userDetails={userDetails}
108 | />
109 |
110 |
111 |
112 |
113 |
114 |
115 | );
116 | }
117 |
118 | export default withRouter(Home);
--------------------------------------------------------------------------------
/React App/src/pages/home/conversation/conversation.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect, useRef } from 'react';
2 | import {
3 | eventEmitter,
4 | sendWebSocketMessage,
5 | } from './../../../services/socket-service';
6 | import { getConversationBetweenUsers } from './../../../services/api-service';
7 |
8 | import './conversation.css'
9 |
10 | const alignMessages = (userDetails, toUserID) => {
11 | const { userID } = userDetails;
12 | return userID !== toUserID;
13 | }
14 |
15 | const scrollMessageContainer = (messageContainer) => {
16 | if (messageContainer.current !== null) {
17 | try {
18 | setTimeout(() => {
19 | messageContainer.current.scrollTop = messageContainer.current.scrollHeight;
20 | }, 100);
21 | } catch (error) {
22 | console.warn(error);
23 | }
24 | }
25 | }
26 |
27 | const getMessageUI = (messageContainer, userDetails, conversations) => {
28 | return (
29 |
30 | {conversations.map((conversation, index) => (
31 | -
37 | {conversation.message}
38 |
39 | ))}
40 |
41 | );
42 | }
43 |
44 | const getInitiateConversationUI = (userDetails) =>{
45 | if (userDetails !== null) {
46 | return (
47 |
48 |
49 | You haven 't chatted with {userDetails.username} in a while,
50 | Say Hi.
51 |
52 |
53 | )
54 | }
55 | }
56 |
57 | function Conversation(props) {
58 | const selectedUser = props.selectedUser;
59 | const userDetails = props.userDetails;
60 |
61 | const messageContainer = useRef(null);
62 | const [conversation, updateConversation] = useState([]);
63 | const [messageLoading, updateMessageLoading] = useState(true);
64 |
65 | useEffect(() => {
66 | if (userDetails && selectedUser) {
67 | (async () => {
68 | const conversationsResponse = await getConversationBetweenUsers(userDetails.userID, selectedUser.userID);
69 | updateMessageLoading(false)
70 | if (conversationsResponse.response) {
71 | updateConversation(conversationsResponse.response);
72 | } else if (conversationsResponse.response === null) {
73 | updateConversation([]);
74 | }
75 | })();
76 | }
77 | }, [userDetails, selectedUser])
78 |
79 | useEffect(() => {
80 | const newMessageSubscription = (messagePayload) => {
81 | if (
82 | selectedUser !== null &&
83 | selectedUser.userID === messagePayload.fromUserID
84 | ) {
85 | updateConversation([...conversation, messagePayload]);
86 | scrollMessageContainer(messageContainer);
87 | }
88 | };
89 |
90 | eventEmitter.on('message-response', newMessageSubscription);
91 |
92 | return () => {
93 | eventEmitter.removeListener('message-response', newMessageSubscription);
94 | };
95 | }, [
96 | conversation,
97 | selectedUser
98 | ]);
99 |
100 | const sendMessage = (event) => {
101 | if (event.key === 'Enter') {
102 | const message = event.target.value;
103 |
104 | if (message === '' || message === undefined || message === null) {
105 | alert(`Message can't be empty.`);
106 | } else if (userDetails.userID === '') {
107 | this.router.navigate(['/']);
108 | } else if (selectedUser === undefined) {
109 | alert(`Select a user to chat.`);
110 | } else {
111 | event.target.value = '';
112 |
113 | const messagePayload = {
114 | fromUserID: userDetails.userID,
115 | message: message.trim(),
116 | toUserID: selectedUser.userID,
117 | };
118 |
119 | sendWebSocketMessage(messagePayload);
120 | updateConversation([...conversation, messagePayload]);
121 | scrollMessageContainer(messageContainer);
122 | }
123 | }
124 | }
125 |
126 | if (messageLoading) {
127 | return (
128 |
131 |
132 | {selectedUser !== null && selectedUser.username
133 | ? 'Loading Messages'
134 | : ' Select a User to chat.'}
135 |
136 |
137 | )
138 | }
139 |
140 | return (
141 |
142 |
143 | {conversation.length > 0
144 | ? getMessageUI(messageContainer, userDetails, conversation)
145 | : getInitiateConversationUI(selectedUser)}
146 |
147 |
148 |
155 |
156 |
157 | );
158 | }
159 |
160 | export default Conversation;
--------------------------------------------------------------------------------
/React App/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/Golang App/handlers/socket-handler.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "log"
7 | "time"
8 |
9 | "github.com/gorilla/websocket"
10 | )
11 |
12 | const (
13 | writeWait = 10 * time.Second
14 | pongWait = 60 * time.Second
15 | pingPeriod = (pongWait * 9) / 10
16 | maxMessageSize = 512
17 | )
18 |
19 | func unRegisterAndCloseConnection(c *Client) {
20 | c.hub.unregister <- c
21 | c.webSocketConnection.Close()
22 | }
23 |
24 | func setSocketPayloadReadConfig(c *Client) {
25 | c.webSocketConnection.SetReadLimit(maxMessageSize)
26 | c.webSocketConnection.SetReadDeadline(time.Now().Add(pongWait))
27 | c.webSocketConnection.SetPongHandler(func(string) error { c.webSocketConnection.SetReadDeadline(time.Now().Add(pongWait)); return nil })
28 | }
29 |
30 | func handleSocketPayloadEvents(client *Client, socketEventPayload SocketEventStruct) {
31 | type chatlistResponseStruct struct {
32 | Type string `json:"type"`
33 | Chatlist interface{} `json:"chatlist"`
34 | }
35 | switch socketEventPayload.EventName {
36 |
37 | case "join":
38 | userID := (socketEventPayload.EventPayload).(string)
39 | userDetails := GetUserByUserID(userID)
40 | if userDetails == (UserDetailsStruct{}) {
41 | log.Println("An invalid user with userID " + userID + " tried to connect to Chat Server.")
42 | } else {
43 | if userDetails.Online == "N" {
44 | log.Println("A logged out user with userID " + userID + " tried to connect to Chat Server.")
45 | } else {
46 | newUserOnlinePayload := SocketEventStruct{
47 | EventName: "chatlist-response",
48 | EventPayload: chatlistResponseStruct{
49 | Type: "new-user-joined",
50 | Chatlist: UserDetailsResponsePayloadStruct{
51 | Online: userDetails.Online,
52 | UserID: userDetails.ID,
53 | Username: userDetails.Username,
54 | },
55 | },
56 | }
57 | BroadcastSocketEventToAllClientExceptMe(client.hub, newUserOnlinePayload, userDetails.ID)
58 |
59 | allOnlineUsersPayload := SocketEventStruct{
60 | EventName: "chatlist-response",
61 | EventPayload: chatlistResponseStruct{
62 | Type: "my-chat-list",
63 | Chatlist: GetAllOnlineUsers(userDetails.ID),
64 | },
65 | }
66 | EmitToSpecificClient(client.hub, allOnlineUsersPayload, userDetails.ID)
67 | }
68 | }
69 | case "disconnect":
70 | if socketEventPayload.EventPayload != nil {
71 |
72 | userID := (socketEventPayload.EventPayload).(string)
73 | userDetails := GetUserByUserID(userID)
74 | UpdateUserOnlineStatusByUserID(userID, "N")
75 |
76 | BroadcastSocketEventToAllClient(client.hub, SocketEventStruct{
77 | EventName: "chatlist-response",
78 | EventPayload: chatlistResponseStruct{
79 | Type: "user-disconnected",
80 | Chatlist: UserDetailsResponsePayloadStruct{
81 | Online: "N",
82 | UserID: userDetails.ID,
83 | Username: userDetails.Username,
84 | },
85 | },
86 | })
87 | }
88 | case "message":
89 | message := (socketEventPayload.EventPayload.(map[string]interface{})["message"]).(string)
90 | fromUserID := (socketEventPayload.EventPayload.(map[string]interface{})["fromUserID"]).(string)
91 | toUserID := (socketEventPayload.EventPayload.(map[string]interface{})["toUserID"]).(string)
92 |
93 | if message != "" && fromUserID != "" && toUserID != "" {
94 |
95 | messagePacket := MessagePayloadStruct{
96 | FromUserID: fromUserID,
97 | Message: message,
98 | ToUserID: toUserID,
99 | }
100 | StoreNewChatMessages(messagePacket)
101 | allOnlineUsersPayload := SocketEventStruct{
102 | EventName: "message-response",
103 | EventPayload: messagePacket,
104 | }
105 | EmitToSpecificClient(client.hub, allOnlineUsersPayload, toUserID)
106 |
107 | }
108 | }
109 | }
110 |
111 | func (c *Client) readPump() {
112 | var socketEventPayload SocketEventStruct
113 |
114 | // Unregistering the client and closing the connection
115 | defer unRegisterAndCloseConnection(c)
116 |
117 | // Setting up the Payload configuration
118 | setSocketPayloadReadConfig(c)
119 |
120 | for {
121 | // ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.
122 | _, payload, err := c.webSocketConnection.ReadMessage()
123 |
124 | decoder := json.NewDecoder(bytes.NewReader(payload))
125 | decoderErr := decoder.Decode(&socketEventPayload)
126 |
127 | if decoderErr != nil {
128 | log.Printf("error: %v", decoderErr)
129 | break
130 | }
131 |
132 | if err != nil {
133 | if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
134 | log.Printf("error ===: %v", err)
135 | }
136 | break
137 | }
138 |
139 | // Getting the proper Payload to send the client
140 | handleSocketPayloadEvents(c, socketEventPayload)
141 | }
142 | }
143 |
144 | func (c *Client) writePump() {
145 | ticker := time.NewTicker(pingPeriod)
146 | defer func() {
147 | ticker.Stop()
148 | c.webSocketConnection.Close()
149 | }()
150 | for {
151 | select {
152 | case payload, ok := <-c.send:
153 |
154 | reqBodyBytes := new(bytes.Buffer)
155 | json.NewEncoder(reqBodyBytes).Encode(payload)
156 | finalPayload := reqBodyBytes.Bytes()
157 |
158 | c.webSocketConnection.SetWriteDeadline(time.Now().Add(writeWait))
159 | if !ok {
160 | c.webSocketConnection.WriteMessage(websocket.CloseMessage, []byte{})
161 | return
162 | }
163 |
164 | w, err := c.webSocketConnection.NextWriter(websocket.TextMessage)
165 | if err != nil {
166 | return
167 | }
168 |
169 | w.Write(finalPayload)
170 |
171 | n := len(c.send)
172 | for i := 0; i < n; i++ {
173 | json.NewEncoder(reqBodyBytes).Encode(<-c.send)
174 | w.Write(reqBodyBytes.Bytes())
175 | }
176 |
177 | if err := w.Close(); err != nil {
178 | return
179 | }
180 | case <-ticker.C:
181 | c.webSocketConnection.SetWriteDeadline(time.Now().Add(writeWait))
182 | if err := c.webSocketConnection.WriteMessage(websocket.PingMessage, nil); err != nil {
183 | return
184 | }
185 | }
186 | }
187 | }
188 |
189 | // CreateNewSocketUser creates a new socket user
190 | func CreateNewSocketUser(hub *Hub, connection *websocket.Conn, userID string) {
191 | client := &Client{
192 | hub: hub,
193 | webSocketConnection: connection,
194 | send: make(chan SocketEventStruct),
195 | userID: userID,
196 | }
197 |
198 | go client.writePump()
199 | go client.readPump()
200 |
201 | client.hub.register <- client
202 | }
203 |
204 | // HandleUserRegisterEvent will handle the Join event for New socket users
205 | func HandleUserRegisterEvent(hub *Hub, client *Client) {
206 | hub.clients[client] = true
207 | handleSocketPayloadEvents(client, SocketEventStruct{
208 | EventName: "join",
209 | EventPayload: client.userID,
210 | })
211 | }
212 |
213 | // HandleUserDisconnectEvent will handle the Disconnect event for socket users
214 | func HandleUserDisconnectEvent(hub *Hub, client *Client) {
215 | _, ok := hub.clients[client]
216 | if ok {
217 | delete(hub.clients, client)
218 | close(client.send)
219 |
220 | handleSocketPayloadEvents(client, SocketEventStruct{
221 | EventName: "disconnect",
222 | EventPayload: client.userID,
223 | })
224 | }
225 | }
226 |
227 | // EmitToSpecificClient will emit the socket event to specific socket user
228 | func EmitToSpecificClient(hub *Hub, payload SocketEventStruct, userID string) {
229 | for client := range hub.clients {
230 | if client.userID == userID {
231 | select {
232 | case client.send <- payload:
233 | default:
234 | close(client.send)
235 | delete(hub.clients, client)
236 | }
237 | }
238 | }
239 | }
240 |
241 | // BroadcastSocketEventToAllClient will emit the socket events to all socket users
242 | func BroadcastSocketEventToAllClient(hub *Hub, payload SocketEventStruct) {
243 | for client := range hub.clients {
244 | select {
245 | case client.send <- payload:
246 | default:
247 | close(client.send)
248 | delete(hub.clients, client)
249 | }
250 | }
251 | }
252 |
253 | // BroadcastSocketEventToAllClientExceptMe will emit the socket events to all socket users,
254 | // except the user who is emitting the event
255 | func BroadcastSocketEventToAllClientExceptMe(hub *Hub, payload SocketEventStruct, myUserID string) {
256 | for client := range hub.clients {
257 | if client.userID != myUserID {
258 | select {
259 | case client.send <- payload:
260 | default:
261 | close(client.send)
262 | delete(hub.clients, client)
263 | }
264 | }
265 | }
266 | }
267 |
--------------------------------------------------------------------------------
/Golang App/handlers/query-handlers.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "os"
7 | "time"
8 |
9 | "go.mongodb.org/mongo-driver/bson"
10 | "go.mongodb.org/mongo-driver/bson/primitive"
11 |
12 | config "private-chat/config"
13 | constants "private-chat/constants"
14 | utils "private-chat/utils"
15 | )
16 |
17 | // UpdateUserOnlineStatusByUserID will update the online status of the user
18 | func UpdateUserOnlineStatusByUserID(userID string, status string) error {
19 | docID, err := primitive.ObjectIDFromHex(userID)
20 | if err != nil {
21 | return nil
22 | }
23 |
24 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("users")
25 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
26 |
27 | _, queryError := collection.UpdateOne(ctx, bson.M{"_id": docID}, bson.M{"$set": bson.M{"online": status}})
28 | defer cancel()
29 |
30 | if queryError != nil {
31 | return errors.New(constants.ServerFailedResponse)
32 | }
33 | return nil
34 | }
35 |
36 | // GetUserByUsername function will return user datails based username
37 | func GetUserByUsername(username string) UserDetailsStruct {
38 | var userDetails UserDetailsStruct
39 |
40 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("users")
41 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
42 |
43 | _ = collection.FindOne(ctx, bson.M{
44 | "username": username,
45 | }).Decode(&userDetails)
46 |
47 | defer cancel()
48 |
49 | return userDetails
50 | }
51 |
52 | // GetUserByUserID function will return user datails based username
53 | func GetUserByUserID(userID string) UserDetailsStruct {
54 | var userDetails UserDetailsStruct
55 |
56 | docID, err := primitive.ObjectIDFromHex(userID)
57 | if err != nil {
58 | return UserDetailsStruct{}
59 | }
60 |
61 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("users")
62 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
63 |
64 | _ = collection.FindOne(ctx, bson.M{
65 | "_id": docID,
66 | }).Decode(&userDetails)
67 |
68 | defer cancel()
69 |
70 | return userDetails
71 | }
72 |
73 | // IsUsernameAvailableQueryHandler function will check username from the database
74 | func IsUsernameAvailableQueryHandler(username string) bool {
75 | userDetails := GetUserByUsername(username)
76 | if userDetails == (UserDetailsStruct{}) {
77 | return true
78 | }
79 | return false
80 | }
81 |
82 | // LoginQueryHandler function will check username from the database
83 | func LoginQueryHandler(userDetailsRequestPayload UserDetailsRequestPayloadStruct) (UserDetailsResponsePayloadStruct, error) {
84 | if userDetailsRequestPayload.Username == "" {
85 | return UserDetailsResponsePayloadStruct{}, errors.New(constants.UsernameCantBeEmpty)
86 | } else if userDetailsRequestPayload.Password == "" {
87 | return UserDetailsResponsePayloadStruct{}, errors.New(constants.PasswordCantBeEmpty)
88 | } else {
89 | userDetails := GetUserByUsername(userDetailsRequestPayload.Username)
90 | if userDetails == (UserDetailsStruct{}) {
91 | return UserDetailsResponsePayloadStruct{}, errors.New(constants.UserIsNotRegisteredWithUs)
92 | }
93 |
94 | if isPasswordOkay := utils.ComparePasswords(userDetailsRequestPayload.Password, userDetails.Password); isPasswordOkay != nil {
95 | return UserDetailsResponsePayloadStruct{}, errors.New(constants.LoginPasswordIsInCorrect)
96 | }
97 |
98 | if onlineStatusError := UpdateUserOnlineStatusByUserID(userDetails.ID, "Y"); onlineStatusError != nil {
99 | return UserDetailsResponsePayloadStruct{}, errors.New(constants.LoginPasswordIsInCorrect)
100 | }
101 |
102 | return UserDetailsResponsePayloadStruct{
103 | UserID: userDetails.ID,
104 | Username: userDetails.Username,
105 | }, nil
106 | }
107 | }
108 |
109 | // RegisterQueryHandler function will check username from the database
110 | func RegisterQueryHandler(userDetailsRequestPayload UserDetailsRequestPayloadStruct) (string, error) {
111 | if userDetailsRequestPayload.Username == "" {
112 | return "", errors.New(constants.UsernameCantBeEmpty)
113 | } else if userDetailsRequestPayload.Password == "" {
114 | return "", errors.New(constants.PasswordCantBeEmpty)
115 | } else {
116 | newPasswordHash, newPasswordHashError := utils.CreatePassword(userDetailsRequestPayload.Password)
117 | if newPasswordHashError != nil {
118 | return "", errors.New(constants.ServerFailedResponse)
119 | }
120 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("users")
121 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
122 |
123 | registrationQueryResponse, registrationError := collection.InsertOne(ctx, bson.M{
124 | "username": userDetailsRequestPayload.Username,
125 | "password": newPasswordHash,
126 | "online": "N",
127 | })
128 | defer cancel()
129 |
130 | registrationQueryObjectID, registrationQueryObjectIDError := registrationQueryResponse.InsertedID.(primitive.ObjectID)
131 |
132 | if onlineStatusError := UpdateUserOnlineStatusByUserID(registrationQueryObjectID.Hex(), "Y"); onlineStatusError != nil {
133 | return " ", errors.New(constants.ServerFailedResponse)
134 | }
135 |
136 | if registrationError != nil || !registrationQueryObjectIDError {
137 | return "", errors.New(constants.ServerFailedResponse)
138 | }
139 |
140 | return registrationQueryObjectID.Hex(), nil
141 | }
142 | }
143 |
144 | // GetAllOnlineUsers function will return the all online users
145 | func GetAllOnlineUsers(userID string) []UserDetailsResponsePayloadStruct {
146 | var onlineUsers []UserDetailsResponsePayloadStruct
147 |
148 | docID, err := primitive.ObjectIDFromHex(userID)
149 | if err != nil {
150 | return onlineUsers
151 | }
152 |
153 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("users")
154 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
155 |
156 | cursor, queryError := collection.Find(ctx, bson.M{
157 | "online": "Y",
158 | "_id": bson.M{
159 | "$ne": docID,
160 | },
161 | })
162 | defer cancel()
163 |
164 | if queryError != nil {
165 | return onlineUsers
166 | }
167 |
168 | for cursor.Next(context.TODO()) {
169 | //Create a value into which the single document can be decoded
170 | var singleOnlineUser UserDetailsStruct
171 | err := cursor.Decode(&singleOnlineUser)
172 |
173 | if err == nil {
174 | onlineUsers = append(onlineUsers, UserDetailsResponsePayloadStruct{
175 | UserID: singleOnlineUser.ID,
176 | Online: singleOnlineUser.Online,
177 | Username: singleOnlineUser.Username,
178 | })
179 | }
180 | }
181 |
182 | return onlineUsers
183 | }
184 |
185 | // StoreNewChatMessages is used for storing a new message
186 | func StoreNewChatMessages(messagePayload MessagePayloadStruct) bool {
187 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("messages")
188 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
189 |
190 | _, registrationError := collection.InsertOne(ctx, bson.M{
191 | "fromUserID": messagePayload.FromUserID,
192 | "message": messagePayload.Message,
193 | "toUserID": messagePayload.ToUserID,
194 | })
195 | defer cancel()
196 |
197 | if registrationError == nil {
198 | return false
199 | }
200 | return true
201 | }
202 |
203 | // GetConversationBetweenTwoUsers will be used to fetch the conversation between two users
204 | func GetConversationBetweenTwoUsers(toUserID string, fromUserID string) []ConversationStruct {
205 | var conversations []ConversationStruct
206 |
207 | collection := config.MongoDBClient.Database(os.Getenv("MONGODB_DATABASE")).Collection("messages")
208 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
209 |
210 | queryCondition := bson.M{
211 | "$or": []bson.M{
212 | {
213 | "$and": []bson.M{
214 | {
215 | "toUserID": toUserID,
216 | },
217 | {
218 | "fromUserID": fromUserID,
219 | },
220 | },
221 | },
222 | {
223 | "$and": []bson.M{
224 | {
225 | "toUserID": fromUserID,
226 | },
227 | {
228 | "fromUserID": toUserID,
229 | },
230 | },
231 | },
232 | },
233 | }
234 |
235 | cursor, queryError := collection.Find(ctx, queryCondition)
236 | defer cancel()
237 |
238 | if queryError != nil {
239 | return conversations
240 | }
241 |
242 | for cursor.Next(context.TODO()) {
243 | //Create a value into which the single document can be decoded
244 | var conversation ConversationStruct
245 | err := cursor.Decode(&conversation)
246 |
247 | if err == nil {
248 | conversations = append(conversations, ConversationStruct{
249 | ID: conversation.ID,
250 | FromUserID: conversation.FromUserID,
251 | ToUserID: conversation.ToUserID,
252 | Message: conversation.Message,
253 | })
254 | }
255 | }
256 | return conversations
257 | }
258 |
--------------------------------------------------------------------------------
/Golang App/handlers/routes-handlers.go:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "encoding/json"
5 | "net/http"
6 | "regexp"
7 |
8 | "github.com/gorilla/mux"
9 |
10 | constants "private-chat/constants"
11 | )
12 |
13 | // RenderHome Rendering the Home Page
14 | func RenderHome(responseWriter http.ResponseWriter, request *http.Request) {
15 | response := APIResponseStruct{
16 | Code: http.StatusOK,
17 | Status: http.StatusText(http.StatusOK),
18 | Message: constants.APIWelcomeMessage,
19 | Response: nil,
20 | }
21 | ReturnResponse(responseWriter, request, response)
22 | }
23 |
24 | //IsUsernameAvailable function will handle the availability of username
25 | func IsUsernameAvailable(responseWriter http.ResponseWriter, request *http.Request) {
26 | type usernameAvailableResposeStruct struct {
27 | IsUsernameAvailable bool `json:"isUsernameAvailable"`
28 | }
29 | var response APIResponseStruct
30 | var IsAlphaNumeric = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$`).MatchString
31 | username := mux.Vars(request)["username"]
32 |
33 | // Checking if username is not empty & has only AlphaNumeric charecters
34 | if !IsAlphaNumeric(username) {
35 | response := APIResponseStruct{
36 | Code: http.StatusBadRequest,
37 | Status: http.StatusText(http.StatusBadRequest),
38 | Message: constants.UsernameCantBeEmpty,
39 | Response: nil,
40 | }
41 | ReturnResponse(responseWriter, request, response)
42 | } else {
43 | isUsernameAvailable := IsUsernameAvailableQueryHandler(username)
44 | if isUsernameAvailable {
45 | response = APIResponseStruct{
46 | Code: http.StatusOK,
47 | Status: http.StatusText(http.StatusOK),
48 | Message: constants.UsernameIsAvailable,
49 | Response: usernameAvailableResposeStruct{
50 | IsUsernameAvailable: isUsernameAvailable,
51 | },
52 | }
53 | } else {
54 | response = APIResponseStruct{
55 | Code: http.StatusOK,
56 | Status: http.StatusText(http.StatusOK),
57 | Message: constants.UsernameIsNotAvailable,
58 | Response: usernameAvailableResposeStruct{
59 | IsUsernameAvailable: isUsernameAvailable,
60 | },
61 | }
62 | }
63 | ReturnResponse(responseWriter, request, response)
64 | }
65 | }
66 |
67 | //Login function will login the users
68 | func Login(responseWriter http.ResponseWriter, request *http.Request) {
69 | var userDetails UserDetailsRequestPayloadStruct
70 |
71 | decoder := json.NewDecoder(request.Body)
72 | requestDecoderError := decoder.Decode(&userDetails)
73 | defer request.Body.Close()
74 |
75 | if requestDecoderError != nil {
76 | response := APIResponseStruct{
77 | Code: http.StatusBadRequest,
78 | Status: http.StatusText(http.StatusBadRequest),
79 | Message: constants.UsernameAndPasswordCantBeEmpty,
80 | Response: nil,
81 | }
82 | ReturnResponse(responseWriter, request, response)
83 | } else {
84 | if userDetails.Username == "" {
85 | response := APIResponseStruct{
86 | Code: http.StatusBadRequest,
87 | Status: http.StatusText(http.StatusBadRequest),
88 | Message: constants.UsernameCantBeEmpty,
89 | Response: nil,
90 | }
91 | ReturnResponse(responseWriter, request, response)
92 | } else if userDetails.Password == "" {
93 | response := APIResponseStruct{
94 | Code: http.StatusInternalServerError,
95 | Status: http.StatusText(http.StatusInternalServerError),
96 | Message: constants.PasswordCantBeEmpty,
97 | Response: nil,
98 | }
99 | ReturnResponse(responseWriter, request, response)
100 | } else {
101 |
102 | userDetails, loginErrorMessage := LoginQueryHandler(userDetails)
103 |
104 | if loginErrorMessage != nil {
105 | response := APIResponseStruct{
106 | Code: http.StatusNotFound,
107 | Status: http.StatusText(http.StatusNotFound),
108 | Message: loginErrorMessage.Error(),
109 | Response: nil,
110 | }
111 | ReturnResponse(responseWriter, request, response)
112 | } else {
113 | response := APIResponseStruct{
114 | Code: http.StatusOK,
115 | Status: http.StatusText(http.StatusOK),
116 | Message: constants.UserLoginCompleted,
117 | Response: userDetails,
118 | }
119 | ReturnResponse(responseWriter, request, response)
120 | }
121 | }
122 | }
123 | }
124 |
125 | //Registertation function will login the users
126 | func Registertation(responseWriter http.ResponseWriter, request *http.Request) {
127 | var userDetailsRequestPayload UserDetailsRequestPayloadStruct
128 |
129 | decoder := json.NewDecoder(request.Body)
130 | requestDecoderError := decoder.Decode(&userDetailsRequestPayload)
131 | defer request.Body.Close()
132 |
133 | if requestDecoderError != nil {
134 | response := APIResponseStruct{
135 | Code: http.StatusBadRequest,
136 | Status: http.StatusText(http.StatusBadRequest),
137 | Message: constants.ServerFailedResponse,
138 | Response: nil,
139 | }
140 | ReturnResponse(responseWriter, request, response)
141 | } else {
142 | if userDetailsRequestPayload.Username == "" {
143 | response := APIResponseStruct{
144 | Code: http.StatusBadRequest,
145 | Status: http.StatusText(http.StatusBadRequest),
146 | Message: constants.UsernameCantBeEmpty,
147 | Response: nil,
148 | }
149 | ReturnResponse(responseWriter, request, response)
150 | } else if userDetailsRequestPayload.Password == "" {
151 | response := APIResponseStruct{
152 | Code: http.StatusInternalServerError,
153 | Status: http.StatusText(http.StatusInternalServerError),
154 | Message: constants.PasswordCantBeEmpty,
155 | Response: nil,
156 | }
157 | ReturnResponse(responseWriter, request, response)
158 | } else {
159 | userObjectID, registrationError := RegisterQueryHandler(userDetailsRequestPayload)
160 | if registrationError != nil {
161 | response := APIResponseStruct{
162 | Code: http.StatusInternalServerError,
163 | Status: http.StatusText(http.StatusInternalServerError),
164 | Message: constants.ServerFailedResponse,
165 | Response: nil,
166 | }
167 | ReturnResponse(responseWriter, request, response)
168 | } else {
169 | response := APIResponseStruct{
170 | Code: http.StatusOK,
171 | Status: http.StatusText(http.StatusOK),
172 | Message: constants.UserRegistrationCompleted,
173 | Response: UserDetailsResponsePayloadStruct{
174 | Username: userDetailsRequestPayload.Username,
175 | UserID: userObjectID,
176 | },
177 | }
178 | ReturnResponse(responseWriter, request, response)
179 | }
180 | }
181 | }
182 | }
183 |
184 | //UserSessionCheck function will check login status of the user
185 | func UserSessionCheck(responseWriter http.ResponseWriter, request *http.Request) {
186 | var IsAlphaNumeric = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$`).MatchString
187 | userID := mux.Vars(request)["userID"]
188 |
189 | if !IsAlphaNumeric(userID) {
190 | response := APIResponseStruct{
191 | Code: http.StatusBadRequest,
192 | Status: http.StatusText(http.StatusBadRequest),
193 | Message: constants.UsernameCantBeEmpty,
194 | Response: nil,
195 | }
196 | ReturnResponse(responseWriter, request, response)
197 | } else {
198 | uerDetails := GetUserByUserID(userID)
199 | if uerDetails == (UserDetailsStruct{}) {
200 | response := APIResponseStruct{
201 | Code: http.StatusOK,
202 | Status: http.StatusText(http.StatusOK),
203 | Message: constants.YouAreNotLoggedIN,
204 | Response: false,
205 | }
206 | ReturnResponse(responseWriter, request, response)
207 | } else {
208 | response := APIResponseStruct{
209 | Code: http.StatusOK,
210 | Status: http.StatusText(http.StatusOK),
211 | Message: constants.YouAreLoggedIN,
212 | Response: uerDetails.Online == "Y",
213 | }
214 | ReturnResponse(responseWriter, request, response)
215 | }
216 | }
217 | }
218 |
219 | //GetMessagesHandler function will fetch the messages between two users
220 | func GetMessagesHandler(responseWriter http.ResponseWriter, request *http.Request) {
221 | var IsAlphaNumeric = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$`).MatchString
222 | toUserID := mux.Vars(request)["toUserID"]
223 | fromUserID := mux.Vars(request)["fromUserID"]
224 |
225 | if !IsAlphaNumeric(toUserID) {
226 | response := APIResponseStruct{
227 | Code: http.StatusBadRequest,
228 | Status: http.StatusText(http.StatusBadRequest),
229 | Message: constants.UsernameCantBeEmpty,
230 | Response: nil,
231 | }
232 | ReturnResponse(responseWriter, request, response)
233 | } else if !IsAlphaNumeric(fromUserID) {
234 | response := APIResponseStruct{
235 | Code: http.StatusBadRequest,
236 | Status: http.StatusText(http.StatusBadRequest),
237 | Message: constants.UsernameCantBeEmpty,
238 | Response: nil,
239 | }
240 | ReturnResponse(responseWriter, request, response)
241 | } else {
242 | conversations := GetConversationBetweenTwoUsers(toUserID, fromUserID)
243 | response := APIResponseStruct{
244 | Code: http.StatusOK,
245 | Status: http.StatusText(http.StatusOK),
246 | Message: constants.UsernameIsAvailable,
247 | Response: conversations,
248 | }
249 | ReturnResponse(responseWriter, request, response)
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/Golang App/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
5 | github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
6 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
7 | github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
8 | github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
9 | github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg=
10 | github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
11 | github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
12 | github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs=
13 | github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
14 | github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
15 | github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk=
16 | github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28=
17 | github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo=
18 | github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk=
19 | github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw=
20 | github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360=
21 | github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg=
22 | github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE=
23 | github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8=
24 | github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
25 | github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
26 | github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
27 | github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
28 | github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ=
29 | github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0=
30 | github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw=
31 | github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
32 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
33 | github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
34 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
35 | github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
36 | github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
37 | github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
38 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
39 | github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg=
40 | github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
41 | github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
42 | github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
43 | github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
44 | github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
45 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
46 | github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
47 | github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
48 | github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4=
49 | github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA=
50 | github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
51 | github.com/klauspost/compress v1.9.5 h1:U+CaK85mrNNb4k8BNOfgJtJ/gr6kswUCFj6miSzVC6M=
52 | github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
53 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
54 | github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
55 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
56 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
57 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
58 | github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE=
59 | github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0=
60 | github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
61 | github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo=
62 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
63 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
64 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
65 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
66 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
67 | github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
68 | github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
69 | github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
70 | github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik=
71 | github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU=
72 | github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
73 | github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
74 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
75 | github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
76 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
77 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
78 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
79 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
80 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
81 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
82 | github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
83 | github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
84 | github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c h1:u40Z8hqBAAQyv+vATcGgV0YCnDjqSL7/q/JyPhhJSPk=
85 | github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I=
86 | github.com/xdg/stringprep v0.0.0-20180714160509-73f8eece6fdc h1:n+nNi93yXLkJvKwXNP9d55HC7lGK4H/SRcwB5IaUZLo=
87 | github.com/xdg/stringprep v0.0.0-20180714160509-73f8eece6fdc/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y=
88 | go.mongodb.org/mongo-driver v1.3.3 h1:9kX7WY6sU/5qBuhm5mdnNWdqaDAQKB2qSZOd5wMEPGQ=
89 | go.mongodb.org/mongo-driver v1.3.3/go.mod h1:MSWZXKOynuguX+JSvwP8i+58jYCXxbia8HS3gZBapIE=
90 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
91 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
92 | golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
93 | golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5 h1:8dUaAV7K4uHsF56JQWkprecIQKdPHtR9jCHF5nB8uzc=
94 | golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
95 | golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
96 | golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
97 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
98 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
99 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
100 | golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
101 | golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
102 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
103 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
104 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
105 | golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
106 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
107 | golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
108 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
109 | golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
110 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
111 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
112 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
113 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
114 | golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
115 | golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
116 | golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
117 | golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
118 | golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
119 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
120 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
121 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
122 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
123 |
--------------------------------------------------------------------------------