1
0

feat: remove gin use net/http

This commit is contained in:
502647092 2018-09-05 10:28:38 +08:00
parent 1893f06bee
commit 9b4497245e

43
main.go
View File

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