Last active
September 27, 2022 13:20
-
-
Save rogerwelin/4d9891b2440e62e88ce34f9f7bdc31b7 to your computer and use it in GitHub Desktop.
websocket gorilla
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
"github.com/gorilla/websocket" | |
) | |
// 1 | |
type longLatStruct struct { | |
Long float64 `json:"longitude"` | |
Lat float64 `json:"latitude"` | |
} | |
var clients = make(map[*websocket.Conn]bool) | |
var broadcast = make(chan *longLatStruct) | |
var upgrader = websocket.Upgrader{ | |
CheckOrigin: func(r *http.Request) bool { | |
return true | |
}, | |
} | |
func main() { | |
// 2 | |
router := mux.NewRouter() | |
router.HandleFunc("/", rootHandler).Methods("GET") | |
router.HandleFunc("/longlat", longLatHandler).Methods("POST") | |
router.HandleFunc("/ws", wsHandler) | |
go echo() | |
log.Fatal(http.ListenAndServe(":8844", router)) | |
} | |
func rootHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "home") | |
} | |
func writer(coord *longLatStruct) { | |
broadcast <- coord | |
} | |
func longLatHandler(w http.ResponseWriter, r *http.Request) { | |
var coordinates longLatStruct | |
if err := json.NewDecoder(r.Body).Decode(&coordinates); err != nil { | |
log.Printf("ERROR: %s", err) | |
http.Error(w, "Bad request", http.StatusTeapot) | |
return | |
} | |
defer r.Body.Close() | |
go writer(&coordinates) | |
} | |
func wsHandler(w http.ResponseWriter, r *http.Request) { | |
ws, err := upgrader.Upgrade(w, r, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// register client | |
clients[ws] = true | |
} | |
// 3 | |
func echo() { | |
for { | |
val := <-broadcast | |
latlong := fmt.Sprintf("%f %f %s", val.Lat, val.Long) | |
// send to every client that is currently connected | |
for client := range clients { | |
err := client.WriteMessage(websocket.TextMessage, []byte(latlong)) | |
if err != nil { | |
log.Printf("Websocket error: %s", err) | |
client.Close() | |
delete(clients, client) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment