-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (89 loc) · 2.44 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"net/http"
"text/template"
"golang.design/x/clipboard"
)
var data []string
var clients = make(map[chan []byte]struct{})
var (
localPortUsage = "Specify the port number on which you want to serve the UI, by default 8080"
)
//go:embed internal/templates/*
var templates embed.FS
func main() {
// localPort represents the arg with flag -p
localPort := flag.String("port", "8080", localPortUsage)
flag.Parse()
err := clipboard.Init()
if err != nil {
panic(err)
}
ch := clipboard.Watch(context.TODO(), clipboard.FmtText)
go copyFromClipBoard(ch)
http.HandleFunc("/", ShowClipboard)
http.HandleFunc("/updates", UpdatesHandler)
fmt.Println("serving the clipboard UI :", *localPort)
err = http.ListenAndServe(":"+*localPort, nil)
if err != nil {
panic("error occured while running clipboard : " + err.Error())
}
}
func copyFromClipBoard(ch <-chan []byte) {
for data_from_clipboard := range ch {
newData := string(data_from_clipboard)
data = append([]string{newData}, data...)
// Serialize data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error marshaling data to JSON:", err)
continue
}
// Send update to clients
for client := range clients {
client <- jsonData
}
}
}
func ShowClipboard(w http.ResponseWriter, r *http.Request) {
indexHTML, err := templates.ReadFile("internal/templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err := template.New("index").Parse(string(indexHTML))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func UpdatesHandler(w http.ResponseWriter, r *http.Request) {
// Set headers for Server-Sent Events
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Create a channel for this client
client := make(chan []byte)
// Register this client
clients[client] = struct{}{}
defer func() {
// Unregister this client
delete(clients, client)
close(client)
}()
// Listen for updates from the channel
for jsonData := range client {
// Send update to the client
fmt.Fprintf(w, "data: %s\n\n", jsonData)
w.(http.Flusher).Flush()
}
}