iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article

Reading Text from the Clipboard

に公開

Another quick tip.

For example, let's consider a scenario where "Hello, world!" is in the clipboard, and you want to retrieve it and output it to standard output.

A well-known package for reading from and writing to the clipboard in Go is github.com/atotto/clipboard. You can write it like this:

sample.go
package main

import (
    "fmt"
    "os"

    "github.com/atotto/clipboard"
)

func main() {
    s, err := clipboard.ReadAll()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Print(s)
}

When you run this:

$ go run sample.go
Hello, world!

You can retrieve the clipboard contents like this.

Originally, on Linux, there is the xsel (or xclip) command, and you can retrieve from the clipboard like so:

$ xsel
Hello, world!

So, what's so great about the github.com/atotto/clipboard package? It's cross-platform compatible, and it works in any environment just by calling the ReadAll/WriteAll functions[1].

As a result, I integrated the github.com/atotto/clipboard package into my own gpgpdump to allow reading ASCII armor text directly from the clipboard.

https://text.baldanders.info/release/2020/12/gpgpdump-v0_11_0-is-released/

It's very convenient when clipboard operations can be easily used within Go code.

脚注
  1. On Linux, the xsel or xclip commands are not installed by default. If you use the github.com/atotto/clipboard package in a UNIX-like environment such as Linux, you need to install the xsel or xclip command beforehand. ↩︎

GitHubで編集を提案

Discussion