Skip to content

Commit cf89cc0

Browse files
committed
Implementing Broadcast(final)
1 parent 80628c4 commit cf89cc0

File tree

8 files changed

+64
-34
lines changed

8 files changed

+64
-34
lines changed

go.mod

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@ module github.com/Euler-B/API-REST_Go
33
go 1.19
44

55
require (
6-
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
7-
github.com/golang-jwt/jwt/v4 v4.4.2 // indirect
8-
github.com/gorilla/mux v1.8.0 // indirect
9-
github.com/gorilla/websocket v1.5.0 // indirect
10-
github.com/joho/godotenv v1.4.0 // indirect
11-
github.com/lib/pq v1.10.7 // indirect
12-
github.com/segmentio/ksuid v1.0.4 // indirect
13-
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect
6+
github.com/golang-jwt/jwt/v4 v4.4.2
7+
github.com/gorilla/mux v1.8.0
8+
github.com/gorilla/websocket v1.5.0
9+
github.com/joho/godotenv v1.4.0
10+
github.com/lib/pq v1.10.7
11+
github.com/segmentio/ksuid v1.0.4
12+
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
1413
)

go.sum

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
2-
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
31
github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs=
42
github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
53
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=

handlers/posts.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,12 @@ func InsertPostHandler(s server.Server) http.HandlerFunc {
6060
if err != nil {
6161
http.Error(w, err.Error(), http.StatusInternalServerError)
6262
return
63+
}
64+
var postMessage = models.WebsocketMessage {
65+
Type: "Post_Created",
66+
Payload: post,
6367
}
68+
s.Hub().Broadcast(postMessage, nil)
6469
w.Header().Set("Content-Type", "application/json")
6570
json.NewEncoder(w).Encode(PostResponse{
6671
Id: post.Id,

main.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"github.com/Euler-B/API-REST_Go/handlers"
1010
"github.com/Euler-B/API-REST_Go/middleware"
1111
"github.com/Euler-B/API-REST_Go/server"
12-
"github.com/Euler-B/API-REST_Go/websocket"
1312
"github.com/gorilla/mux"
1413
"github.com/joho/godotenv"
1514
)
@@ -39,8 +38,7 @@ func main() {
3938
}
4039

4140
func BindRoutes(s server.Server, r *mux.Router) {
42-
hub := websocket.NewHub()
43-
41+
4442
r.Use(middleware.CheckAuthMiddleware(s))
4543

4644
r.HandleFunc("/", handlers.HomeHandler(s)).Methods(http.MethodGet)
@@ -55,6 +53,5 @@ func BindRoutes(s server.Server, r *mux.Router) {
5553
r.HandleFunc("/posts/{id}", handlers.DeletePostHandler(s)).Methods(http.MethodDelete)
5654
r.HandleFunc("/posts", handlers.ListPostHandler(s)).Methods(http.MethodGet)
5755

58-
go hub.Run()
59-
r.HandleFunc("/ws", hub.HandleWebSocket)
56+
r.HandleFunc("/ws", s.Hub().HandleWebSocket)
6057
}

models/message.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package models
2+
3+
type WebsocketMessage struct {
4+
Type string `json:"type"`
5+
Payload interface{} `json:"payload"`
6+
}
7+

server/server.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
"github.com/Euler-B/API-REST_Go/repository"
1212
"github.com/Euler-B/API-REST_Go/database"
13+
"github.com/Euler-B/API-REST_Go/websocket"
1314

1415
)
1516

@@ -21,18 +22,24 @@ type Config struct {
2122

2223
type Server interface {
2324
Config() *Config
25+
Hub() *websocket.Hub
2426
}
2527

2628
type Broker struct {
2729
config *Config
2830
router *mux.Router
31+
hub *websocket.Hub
2932

3033
}
3134

3235
func (b *Broker) Config() *Config {
3336
return b.config
3437
}
3538

39+
func (b *Broker) Hub() *websocket.Hub {
40+
return b.hub
41+
}
42+
3643
func NewServer(ctx context.Context, config *Config) (*Broker, error) {
3744
if config.Port == "" {
3845
return nil, errors.New("el puerto es requerido")
@@ -47,6 +54,7 @@ func NewServer(ctx context.Context, config *Config) (*Broker, error) {
4754
broker := &Broker{
4855
config: config,
4956
router: mux.NewRouter(),
57+
hub: websocket.NewHub(),
5058
}
5159

5260
return broker, nil
@@ -60,6 +68,7 @@ func (b *Broker) Start (binder func(s Server, r *mux.Router)) {
6068
if err != nil {
6169
log.Fatal(err)
6270
}
71+
go b.hub.Run()
6372
repository.SetRepository(repo)
6473

6574
log.Println("Inicializando servidor en el Puerto", b.Config().Port)

websocket/client.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import (
55
)
66

77
type Client struct {
8-
hub *Hub
9-
id string
10-
socket *websocket.Conn
8+
hub *Hub
9+
id string
10+
socket *websocket.Conn
1111
outbound chan []byte
1212
}
1313

@@ -22,12 +22,17 @@ func NewClient (hub *Hub, socket *websocket.Conn) *Client {
2222
func (c *Client) Write() {
2323
for {
2424
select {
25-
case message, ok := <- c.outbound:
25+
case message, ok := <-c.outbound:
2626
if !ok {
2727
c.socket.WriteMessage(websocket.CloseMessage, []byte{})
2828
return
2929
}
3030
c.socket.WriteMessage(websocket.TextMessage, message)
31-
3231
}
32+
}
3333
}
34+
35+
func (c *Client) Close() {
36+
c.socket.Close()
37+
close(c.outbound)
38+
}

websocket/hub.go

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package websocket
22

33
import (
4-
"http"
5-
"log"
4+
"encoding/json"
65
"net/http"
6+
"log"
77
"sync"
88

99
"github.com/gorilla/websocket"
@@ -28,18 +28,6 @@ func NewHub() *Hub {
2828
}
2929
}
3030

31-
func (hub *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
32-
socket, err := upgrader.Upgrade(w, r, nil)
33-
if err != nil {
34-
log.Println(err)
35-
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
36-
}
37-
client := NewClient(hub, socket)
38-
hub.register <- client
39-
40-
go client.Write()
41-
}
42-
4331
func (hub *Hub) Run() {
4432
for {
4533
select {
@@ -62,6 +50,7 @@ func (hub *Hub) onConnect(client *Client) {
6250

6351
func (hub *Hub) onDisconnect(client *Client) {
6452
log.Println("Client Disconnected", client.socket.RemoteAddr())
53+
6554
client.socket.Close()
6655
hub.mutex.Lock()
6756
defer hub.mutex.Unlock()
@@ -75,4 +64,25 @@ func (hub *Hub) onDisconnect(client *Client) {
7564
copy(hub.clients[i:], hub.clients[i+1:])
7665
hub.clients[len(hub.clients) - 1] = nil
7766
hub.clients = hub.clients[:len(hub.clients) - 1]
67+
}
68+
69+
func (hub *Hub) Broadcast(message interface{}, ignore *Client) {
70+
data, _ := json.Marshal(message)
71+
for _, client := range hub.clients {
72+
if client != ignore {
73+
client.outbound <-data
74+
}
75+
}
76+
}
77+
78+
func (hub *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
79+
socket, err := upgrader.Upgrade(w, r, nil)
80+
if err != nil {
81+
log.Println(err)
82+
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
83+
}
84+
client := NewClient(hub, socket)
85+
hub.register <- client
86+
87+
go client.Write()
7888
}

0 commit comments

Comments
 (0)