feat: remove gin use net/http
This commit is contained in:
parent
1893f06bee
commit
9b4497245e
43
main.go
43
main.go
@ -8,7 +8,6 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"yumc.pw/cloud/clipboard-sync/lib/clipboard"
|
||||
)
|
||||
|
||||
@ -21,7 +20,7 @@ func main() {
|
||||
if clipboard.Unsupported {
|
||||
panic("Unsupported On This Machine")
|
||||
}
|
||||
readClipboard(*a)
|
||||
syncClipboard(*a)
|
||||
} else {
|
||||
startServer(*b)
|
||||
}
|
||||
@ -35,34 +34,45 @@ const (
|
||||
func startServer(b string) {
|
||||
text := ""
|
||||
time := time.Now().Unix()
|
||||
g := gin.New()
|
||||
g.GET("/", func(c *gin.Context) {
|
||||
c.Header(textHeader, text)
|
||||
c.Header(timeHeader, strconv.FormatInt(time, 10))
|
||||
http.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case "GET":
|
||||
resp.Header().Add(textHeader, text)
|
||||
resp.Header().Add(timeHeader, strconv.FormatInt(time, 10))
|
||||
break
|
||||
case "POST":
|
||||
text = req.Header.Get(textHeader)
|
||||
time, _ = strconv.ParseInt(req.Header.Get(timeHeader), 10, 64)
|
||||
fmt.Printf("Client %s Update Clipboard...\n", req.RemoteAddr)
|
||||
break
|
||||
}
|
||||
})
|
||||
g.POST("/", func(c *gin.Context) {
|
||||
text = c.Query("text")
|
||||
time, _ = strconv.ParseInt(c.Query("time"), 10, 64)
|
||||
})
|
||||
g.Run(b)
|
||||
fmt.Println("Start Server Listen On: " + b)
|
||||
http.ListenAndServe(b, nil)
|
||||
}
|
||||
|
||||
func readClipboard(a string) {
|
||||
func syncClipboard(a string) {
|
||||
old, _ := clipboard.ReadAll()
|
||||
updateTime := time.Now().Unix()
|
||||
client := &http.Client{}
|
||||
address := a + "?text=%s&time=%s"
|
||||
address := a
|
||||
fmt.Printf("Start Client Connect to Server %s\n", address)
|
||||
for {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
text, _ := clipboard.ReadAll()
|
||||
if old != text {
|
||||
old = text
|
||||
updateTime = time.Now().Unix()
|
||||
request, _ := http.NewRequest("POST",
|
||||
fmt.Sprintf(address, encode(text), strconv.FormatInt(updateTime, 10)), nil)
|
||||
request, _ := http.NewRequest("POST", address, nil)
|
||||
request.Header.Add(textHeader, encode(text))
|
||||
request.Header.Add(timeHeader, strconv.FormatInt(updateTime, 10))
|
||||
client.Do(request)
|
||||
} else {
|
||||
response, _ := http.Get(a)
|
||||
response, err := http.Get(a)
|
||||
if err != nil {
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
texts, ok := response.Header[textHeader]
|
||||
if ok {
|
||||
sText := decode(texts[0])
|
||||
@ -71,6 +81,7 @@ func readClipboard(a string) {
|
||||
old = sText
|
||||
updateTime = sTime
|
||||
clipboard.WriteAll(sText)
|
||||
fmt.Printf("Update Clipboard: %s\n", sText)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user