'Golang: statically finding all strings in code

I would like to parse a package and output all of the strings in the code. The specific use case is to collect sql strings and run them through a sql parser, but that's a separate issue.

Is the best way to do this to just parse this line by line? Or is it possible to regex this or something? I imagine that some cases might be nontrivial, such as multiline strings:

str := "This is
the full
string"

// want > This is the full string
go


Solution 1:[1]

Use the go/scanner package to scan for strings in Go source code:

src, err := os.ReadFile(fname)
if err != nil {
    /// handle error
}

// Create *token.File to scan.
fset := token.NewFileSet()
file := fset.AddFile(fname, fset.Base(), len(src))

var s scanner.Scanner
s.Init(file, src, nil, 0)

for {
    pos, tok, lit := s.Scan()
    if tok == token.EOF {
        break
    }
    if tok == token.STRING {
        s, _ := strconv.Unquote(lit)
        fmt.Printf("%s: %s\n", fset.Position(pos), s)
    }
}

https://go.dev/play/p/849QsbqVhho

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1