main.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html/template"
  6. "log"
  7. "net/http"
  8. "time"
  9. "github.com/gorilla/websocket"
  10. "github.com/icrowley/fake"
  11. )
  12. var upgrader = websocket.Upgrader{
  13. ReadBufferSize: 1024,
  14. WriteBufferSize: 1024,
  15. CheckOrigin: func(r *http.Request) bool {
  16. return true
  17. },
  18. }
  19. func sendNewMsgNotifications(client *websocket.Conn) {
  20. ticker := time.NewTicker(3 * time.Second)
  21. for {
  22. w, err := client.NextWriter(websocket.TextMessage)
  23. if err != nil {
  24. ticker.Stop()
  25. break
  26. }
  27. msg := newMessage()
  28. w.Write(msg)
  29. w.Close()
  30. <-ticker.C
  31. }
  32. }
  33. func main() {
  34. tmpl := template.Must(template.ParseFiles("index.html"))
  35. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  36. tmpl.Execute(w, nil)
  37. })
  38. http.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) {
  39. ws, err := upgrader.Upgrade(w, r, nil)
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. go sendNewMsgNotifications(ws)
  44. })
  45. fmt.Println("starting server at :8080")
  46. http.ListenAndServe(":8080", nil)
  47. }
  48. func newMessage() []byte {
  49. data, _ := json.Marshal(map[string]string{
  50. "email": fake.EmailAddress(),
  51. "name": fake.FirstName() + " " + fake.LastName(),
  52. "subject": fake.Product() + " " + fake.Model(),
  53. })
  54. return data
  55. }