/go-chat-app-websocket

Simple chat app using go websocket

Primary LanguageGo

Chat APP

Simple chat app using gorilla websocket

Demo screenshot app

Goal

Installation & Run

First, Make sure you have set up $GOPATH.

# Download this project
go get github.com/jojoarianto/go-chat-app-websocket

# It's take several minute to download project

Run

# move to project directory
cd $GOPATH/src/github.com/jojoarianto/go-chat-app-websocket

# run golang project
go run main.go

# Visit : http://localhost:8000/

Structure Design

  • Domain
    • Define struct represent mapping to data model
      • message.go
  • Interfaces
    • HTTP handler
    • Websocket handler
    • Respond handler
  • Static
    • Static assets
      • .png .jpeg
      • .css
    • index.html

Model Data

Message (Pesan)

type Message struct {
	ID             xid.ID       `json:"id"`
	Sender         string       `json:"sender,omitempty"`
	ContentMessage string       `json:"content_message"`
	CreatedAt      time.Time    `json:"created_at"`
}

API endpoint for sending a message

POST localhost:8000/sent

Request with data json

{
    "content_message": "Hi Chat App"
}

or using curl

curl --request POST \
  --url http://localhost:8000/sent \
  --header 'content-type: application/json' \
  --data '{
  	    "content_message": "Hi Chat App"
    }'

Respond

{
  "id": "bhgi9mml0s15jsg5c260",
  "sender": "Anonim",
  "content_message": "Hi Chat App",
  "created_at": "2019-02-11T14:31:38.711328+07:00"
}

API endpoint for collect message that has been sent out

GET localhost:8000/sent

Request with hit http://localhost:8000/sent

or using curl

curl --request GET \
  --url http://localhost:8000/sent

Respond

[
  ...
  {
    "id": "bhgibael0s15jsg5c27g",
    "sender": "Anonim",
    "content_message": "Ada apa",
    "created_at": "2019-02-11T14:35:05.886498+07:00"
  },
  {
    "id": "bhgibcml0s15jsg5c28g",
    "sender": "Anonim",
    "content_message": "tidak ada apa apa",
    "created_at": "2019-02-11T14:35:14.373446+07:00"
  }
  ...
]

Display Message on Websocket (Realtime)

Websocket ws://localhost:8000/ws

Open on browser http://localhost:8000

or using curl

curl --include \
     --no-buffer \
     --header "Connection: Upgrade" \
     --header "Upgrade: websocket" \
     --header "Host: localhost:8000" \
     --header "Origin: http://localhost:8000" \
     --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
     --header "Sec-WebSocket-Version: 13" \
     http://localhost:8000/ws

Unit Test

# move to interfaces folder
cd $GOPATH/src/github.com/jojoarianto/go-chat-app-websocket/interfaces

# run golang test
go test -V

Libraries

Demo Screenshot

demo-png