how to get copied text from clipboard on Golang [Mac]

Viewed 35

first of all I'm beginner of Golang

I wonder how to get copied text from clipboard on GoLang

I've searched about three packages but I don't know the way yet

"github.com/atotto/clipboard"
"github.com/d-tsuji/clipboard"
"golang.design/x/clipboard"

I just want to get copied text like this

this is python code

copy_string = pyperclip.paste()

help me guys

2 Answers

That will depend on your OS. That is why packages you mention have _unix.go _windows.go _darwing.go etc.

There is no copy function from std lib if that is your question!

On mac, there are two function available to you: pbpaste and pbcopy.

So if you want to copy/paste on mac without a library:

func copy(content string) error {
    cmd := exec.Command("pbcopy")
    in, err := cmd.StdinPipe()
    if err != nil {
        return err
    }
    if err := cmd.Start(); err != nil {
        return err
    }
    if _, err := in.Write([]byte(content)); err != nil {
        return err
    }
    if err := in.Close(); err != nil {
        return err
    }
    return cmd.Wait()
}


func paste() (content string, err error) {
    cmd := exec.Command("pbpaste")
    out, err := cmd.Output()
    return string(out), err
}

This is what I'm looking for I hope this code will help someone like me

import "github.com/d-tsuji/clipboard"

text, err := clipboard.Get()
fmt.Println(text)
Related