github.com/xxf098/lite-proxy@v0.15.1-0.20230422081941-12c69f323218/wasm/main.go (about) 1 package main 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "fmt" 7 "log" 8 "strings" 9 "syscall/js" 10 11 "github.com/skip2/go-qrcode" 12 ) 13 14 func printMessage(this js.Value, inputs []js.Value) interface{} { 15 callback := inputs[len(inputs)-1] 16 message := inputs[0].String() 17 callback.Invoke(js.Null(), strings.ToUpper(message)) 18 return nil 19 } 20 21 type Item struct { 22 Gid string `json:"gid"` 23 Link string `json:"link"` 24 Size int `json:"size"` 25 } 26 27 func wasmQRcode(this js.Value, inputs []js.Value) interface{} { 28 items := []Item{} 29 jsonItems := inputs[0].String() 30 log.Println(jsonItems) 31 err := json.Unmarshal([]byte(jsonItems), &items) 32 if err != nil { 33 return nil 34 } 35 ch := make(chan struct{}, 3) 36 for _, v := range items { 37 go func(eid string, text string, size int) { 38 defer func() { 39 ch <- struct{}{} 40 }() 41 document := js.Global().Get("document") 42 elem := document.Call("getElementById", eid) 43 elem.Call("setAttribute", "title", text) 44 var bytes []byte 45 bytes, err := qrcode.Encode(text, qrcode.High, size) 46 if err != nil { 47 return 48 } 49 imgData := "data:image/png;base64," + base64.StdEncoding.EncodeToString(bytes) 50 html := fmt.Sprintf(`<canvas width="%d" height="%d" style="display: none;"></canvas> 51 <img style="display: block;" src="%s">`, size, size, imgData) 52 elem.Set("innerHTML", html) 53 }(v.Gid, v.Link, v.Size) 54 <-ch 55 } 56 57 return nil 58 } 59 60 func main() { 61 js.Global().Set("printMessage", js.FuncOf(printMessage)) 62 js.Global().Set("wasmQRcode", js.FuncOf(wasmQRcode)) 63 select {} 64 }