I am trying to use one the functionality provided by go linter in my code. If you use a name like GetId
or ServiceUrl
in go, the linter warns you that the name should be GetID
or ServiceURL
. How could I achieve the same thing in my code. For example if in my I code I have a string GetId
, how could I convert it to a golang compatible identifier (in this case GetID
).
The names GetId
, getId
and ServeURL
are all valid, they just don't follow style guidelines. The name getId
should be changed to getID
to follow the guidelines. See the initialisms section of guidelines for more information about these names.
The lint package does not provide an API to get the replacement text for an identifier. It is, however, possible to construct a source file with the identifier, feed it to the linter and parse the problem. Something like this:
import (
"bytes"
"fmt"
"golang.org/x/lint"
"strings"
)
func checkName(s string) (string, error) {
var buf bytes.Buffer
fmt.Fprintf(&buf, "// Package main is awesome
package main
// %s is wonderful
var %s int
", s, s)
var l lint.Linter
problems, err := l.Lint("", buf.Bytes())
if err != nil {
return "", err
}
if len(problems) >= 1 {
t := problems[0].Text
if i := strings.Index(t, " should be "); i >= 0 {
return t[i+len(" should be "):], nil
}
}
return "", nil
}
The function call checkName("getId")
returns "getID"
.