From 81777e5ed5159de23797bff2ef7142dda9de708c Mon Sep 17 00:00:00 2001 From: Matt Robenolt Date: Fri, 17 Nov 2023 10:13:54 -0800 Subject: [PATCH] Replace usages of bytes.Buffer with strings.Builder (#14539) Signed-off-by: Matt Robenolt --- go/bytes2/buffer.go | 2 +- .../collations/integration/collations_test.go | 6 +-- go/mysql/sqlerror/sql_error.go | 7 ++- go/sqltypes/bind_variables.go | 4 +- go/sqltypes/testing.go | 7 ++- go/sqltypes/value_test.go | 8 ++-- go/stats/opentsdb/collector.go | 3 +- go/tools/release-notes/release_notes.go | 25 +++++------ go/vt/binlog/binlog_streamer.go | 8 ++-- go/vt/hook/hook.go | 7 ++- go/vt/key/destination.go | 9 ++-- go/vt/logutil/logger.go | 17 ++++---- go/vt/mysqlctl/mycnf_gen.go | 10 ++--- go/vt/mysqlctl/mysqld.go | 4 +- go/vt/schemadiff/schema.go | 3 +- go/vt/servenv/status.go | 7 ++- go/vt/sqlparser/normalizer_test.go | 4 +- go/vt/sqlparser/parse_next_test.go | 3 +- go/vt/sqlparser/parse_test.go | 7 ++- go/vt/throttler/result.go | 4 +- go/vt/vtctl/workflow/server.go | 24 +++++------ go/vt/vtexplain/vtexplain.go | 14 +++--- go/vt/vtgate/engine/set.go | 9 +--- go/vt/vtgate/vindexes/consistent_lookup.go | 11 ++--- go/vt/vtgate/vindexes/lookup_internal.go | 18 ++++---- go/vt/vtorc/inst/instance_dao.go | 43 ++++++++++--------- go/vt/vttablet/sysloglogger/sysloglogger.go | 6 ++- .../tabletserver/tabletenv/logstats_test.go | 4 +- go/vt/vttest/local_cluster.go | 10 ++--- go/vt/wrangler/schema.go | 6 +-- go/vt/zkctl/zkconf.go | 17 ++++---- 31 files changed, 143 insertions(+), 164 deletions(-) diff --git a/go/bytes2/buffer.go b/go/bytes2/buffer.go index 1725274c43c..48561c5e493 100644 --- a/go/bytes2/buffer.go +++ b/go/bytes2/buffer.go @@ -65,7 +65,7 @@ func (buf *Buffer) String() string { // is _not_ allocated, so modifying this buffer after calling StringUnsafe will lead // to undefined behavior. func (buf *Buffer) StringUnsafe() string { - return *(*string)(unsafe.Pointer(&buf.bytes)) + return unsafe.String(unsafe.SliceData(buf.bytes), len(buf.bytes)) } // Reset is equivalent to bytes.Buffer.Reset. diff --git a/go/mysql/collations/integration/collations_test.go b/go/mysql/collations/integration/collations_test.go index c8f53eeb242..e5362608e75 100644 --- a/go/mysql/collations/integration/collations_test.go +++ b/go/mysql/collations/integration/collations_test.go @@ -59,7 +59,7 @@ func getSQLQueries(t *testing.T, testfile string) []string { defer tf.Close() var chunks []string - var curchunk bytes.Buffer + var curchunk strings.Builder addchunk := func() { if curchunk.Len() > 0 { @@ -219,8 +219,8 @@ func TestCollationsOnMysqld(t *testing.T) { } func TestRemoteKanaSensitivity(t *testing.T) { - var Kana1 = []byte("の東京ノ") - var Kana2 = []byte("ノ東京の") + Kana1 := []byte("の東京ノ") + Kana2 := []byte("ノ東京の") testRemoteComparison(t, nil, []testcmp{ {"utf8mb4_0900_as_cs", Kana1, Kana2}, diff --git a/go/mysql/sqlerror/sql_error.go b/go/mysql/sqlerror/sql_error.go index 30ce99d681a..7a71070a70c 100644 --- a/go/mysql/sqlerror/sql_error.go +++ b/go/mysql/sqlerror/sql_error.go @@ -17,7 +17,6 @@ limitations under the License. package sqlerror import ( - "bytes" "fmt" "regexp" "strconv" @@ -53,17 +52,17 @@ func NewSQLError(number ErrorCode, sqlState string, format string, args ...any) // Error implements the error interface func (se *SQLError) Error() string { - buf := &bytes.Buffer{} + var buf strings.Builder buf.WriteString(se.Message) // Add MySQL errno and SQLSTATE in a format that we can later parse. // There's no avoiding string parsing because all errors // are converted to strings anyway at RPC boundaries. // See NewSQLErrorFromError. - fmt.Fprintf(buf, " (errno %v) (sqlstate %v)", se.Num, se.State) + fmt.Fprintf(&buf, " (errno %v) (sqlstate %v)", se.Num, se.State) if se.Query != "" { - fmt.Fprintf(buf, " during query: %s", sqlparser.TruncateForLog(se.Query)) + fmt.Fprintf(&buf, " during query: %s", sqlparser.TruncateForLog(se.Query)) } return buf.String() diff --git a/go/sqltypes/bind_variables.go b/go/sqltypes/bind_variables.go index 18beda37702..9b8969bc814 100644 --- a/go/sqltypes/bind_variables.go +++ b/go/sqltypes/bind_variables.go @@ -17,10 +17,10 @@ limitations under the License. package sqltypes import ( - "bytes" "errors" "fmt" "strconv" + "strings" "google.golang.org/protobuf/proto" @@ -418,7 +418,7 @@ func FormatBindVariables(bindVariables map[string]*querypb.BindVariable, full, a } if asJSON { - var buf bytes.Buffer + var buf strings.Builder buf.WriteString("{") first := true for k, v := range out { diff --git a/go/sqltypes/testing.go b/go/sqltypes/testing.go index 3894635eae0..1c191b8c5e7 100644 --- a/go/sqltypes/testing.go +++ b/go/sqltypes/testing.go @@ -17,7 +17,6 @@ limitations under the License. package sqltypes import ( - "bytes" crand "crypto/rand" "encoding/base64" "encoding/hex" @@ -155,13 +154,13 @@ func TestTuple(vals ...Value) Value { // PrintResults prints []*Results into a string. // This function should only be used for testing. func PrintResults(results []*Result) string { - b := new(bytes.Buffer) + var b strings.Builder for i, r := range results { if i == 0 { - fmt.Fprintf(b, "%v", r) + fmt.Fprintf(&b, "%v", r) continue } - fmt.Fprintf(b, ", %v", r) + fmt.Fprintf(&b, ", %v", r) } return b.String() } diff --git a/go/sqltypes/value_test.go b/go/sqltypes/value_test.go index 86c751f3d0d..10a46e09a9e 100644 --- a/go/sqltypes/value_test.go +++ b/go/sqltypes/value_test.go @@ -463,13 +463,13 @@ func TestEncode(t *testing.T) { outASCII: "'YQ=='", }} for _, tcase := range testcases { - buf := &bytes.Buffer{} - tcase.in.EncodeSQL(buf) + var buf strings.Builder + tcase.in.EncodeSQL(&buf) if tcase.outSQL != buf.String() { t.Errorf("%v.EncodeSQL = %q, want %q", tcase.in, buf.String(), tcase.outSQL) } - buf = &bytes.Buffer{} - tcase.in.EncodeASCII(buf) + buf.Reset() + tcase.in.EncodeASCII(&buf) if tcase.outASCII != buf.String() { t.Errorf("%v.EncodeASCII = %q, want %q", tcase.in, buf.String(), tcase.outASCII) } diff --git a/go/stats/opentsdb/collector.go b/go/stats/opentsdb/collector.go index 9b870815067..d2c40432e7f 100644 --- a/go/stats/opentsdb/collector.go +++ b/go/stats/opentsdb/collector.go @@ -17,7 +17,6 @@ limitations under the License. package opentsdb import ( - "bytes" "encoding/json" "expvar" "strings" @@ -65,7 +64,7 @@ func (dc *collector) addFloat(metric string, val float64, tags map[string]string // Also make everything lowercase, since opentsdb is case sensitive and lowercase // simplifies the convention. sanitize := func(text string) string { - var b bytes.Buffer + var b strings.Builder for _, r := range text { if unicode.IsDigit(r) || unicode.IsLetter(r) || r == '-' || r == '_' || r == '/' || r == '.' { b.WriteRune(r) diff --git a/go/tools/release-notes/release_notes.go b/go/tools/release-notes/release_notes.go index 1673d6a5160..1a8105a6f38 100644 --- a/go/tools/release-notes/release_notes.go +++ b/go/tools/release-notes/release_notes.go @@ -17,7 +17,6 @@ limitations under the License. package main import ( - "bytes" "encoding/json" "fmt" "log" @@ -79,9 +78,7 @@ type ( } ) -var ( - releaseNotesPath = `changelog/` -) +var releaseNotesPath = `changelog/` const ( releaseNotesPathGitHub = `https://github.com/vitessio/vitess/blob/main/` @@ -141,7 +138,7 @@ func (rn *releaseNote) generate(rnFile, changelogFile *os.File) error { // Generate the release notes rn.PathToChangeLogFileOnGH = releaseNotesPathGitHub + path.Join(rn.SubDirPath, "changelog.md") if rnFile == nil { - rnFile, err = os.OpenFile(path.Join(rn.SubDirPath, "release_notes.md"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) + rnFile, err = os.OpenFile(path.Join(rn.SubDirPath, "release_notes.md"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { return err } @@ -155,7 +152,7 @@ func (rn *releaseNote) generate(rnFile, changelogFile *os.File) error { // Generate the changelog if changelogFile == nil { - changelogFile, err = os.OpenFile(path.Join(rn.SubDirPath, "changelog.md"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) + changelogFile, err = os.OpenFile(path.Join(rn.SubDirPath, "changelog.md"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { return err } @@ -304,11 +301,11 @@ func getStringForPullRequestInfos(prPerType prsByType) (string, error) { data := createSortedPrTypeSlice(prPerType) t := template.Must(template.New("markdownTemplatePR").Parse(markdownTemplatePR)) - buff := bytes.Buffer{} - if err := t.ExecuteTemplate(&buff, "markdownTemplatePR", data); err != nil { + var buf strings.Builder + if err := t.ExecuteTemplate(&buf, "markdownTemplatePR", data); err != nil { return "", err } - return buff.String(), nil + return buf.String(), nil } func getStringForKnownIssues(issues []knownIssue) (string, error) { @@ -316,11 +313,11 @@ func getStringForKnownIssues(issues []knownIssue) (string, error) { return "", nil } t := template.Must(template.New("markdownTemplateKnownIssues").Parse(markdownTemplateKnownIssues)) - buff := bytes.Buffer{} - if err := t.ExecuteTemplate(&buff, "markdownTemplateKnownIssues", issues); err != nil { + var buf strings.Builder + if err := t.ExecuteTemplate(&buf, "markdownTemplateKnownIssues", issues); err != nil { return "", err } - return buff.String(), nil + return buf.String(), nil } func groupAndStringifyPullRequest(pris []pullRequestInformation) (string, error) { @@ -336,9 +333,7 @@ func groupAndStringifyPullRequest(pris []pullRequestInformation) (string, error) } func main() { - var ( - versionName, summaryFile string - ) + var versionName, summaryFile string pflag.StringVarP(&versionName, "version", "v", "", "name of the version (has to be the following format: v11.0.0)") pflag.StringVarP(&summaryFile, "summary", "s", "", "readme file on which there is a summary of the release") pflag.Parse() diff --git a/go/vt/binlog/binlog_streamer.go b/go/vt/binlog/binlog_streamer.go index abbf73ba506..d62fcc3a915 100644 --- a/go/vt/binlog/binlog_streamer.go +++ b/go/vt/binlog/binlog_streamer.go @@ -251,8 +251,8 @@ func (bls *Streamer) parseEvents(ctx context.Context, events <-chan mysql.Binlog var statements []FullBinlogStatement var format mysql.BinlogFormat var gtid replication.GTID - var pos = bls.startPos - var autocommit = true + pos := bls.startPos + autocommit := true var err error // Remember the RBR state. @@ -723,7 +723,7 @@ func (bls *Streamer) appendDeletes(statements []FullBinlogStatement, tce *tableC } // writeValuesAsSQL is a helper method to print the values as SQL in the -// provided bytes.Buffer. It also returns the value for the keyspaceIDColumn, +// provided strings.Builder. It also returns the value for the keyspaceIDColumn, // and the array of values for the PK, if necessary. func writeValuesAsSQL(sql *sqlparser.TrackedBuffer, tce *tableCacheEntry, rs *mysql.Rows, rowIndex int, getPK bool) (sqltypes.Value, []sqltypes.Value, error) { valueIndex := 0 @@ -794,7 +794,7 @@ func writeValuesAsSQL(sql *sqlparser.TrackedBuffer, tce *tableCacheEntry, rs *my } // writeIdentifiersAsSQL is a helper method to print the identifies as SQL in the -// provided bytes.Buffer. It also returns the value for the keyspaceIDColumn, +// provided strings.Builder. It also returns the value for the keyspaceIDColumn, // and the array of values for the PK, if necessary. func writeIdentifiersAsSQL(sql *sqlparser.TrackedBuffer, tce *tableCacheEntry, rs *mysql.Rows, rowIndex int, getPK bool) (sqltypes.Value, []sqltypes.Value, error) { valueIndex := 0 diff --git a/go/vt/hook/hook.go b/go/vt/hook/hook.go index 6cee35e4241..4f402cdcb44 100644 --- a/go/vt/hook/hook.go +++ b/go/vt/hook/hook.go @@ -17,7 +17,6 @@ limitations under the License. package hook import ( - "bytes" "context" "errors" "fmt" @@ -147,7 +146,7 @@ func (hook *Hook) ExecuteContext(ctx context.Context) (result *HookResult) { } // Run it. - var stdout, stderr bytes.Buffer + var stdout, stderr strings.Builder cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -234,7 +233,7 @@ func (hook *Hook) ExecuteAsWritePipe(out io.Writer) (io.WriteCloser, WaitFunc, i return nil, nil, HOOK_GENERIC_ERROR, fmt.Errorf("failed to configure stdin: %v", err) } cmd.Stdout = out - var stderr bytes.Buffer + var stderr strings.Builder cmd.Stderr = &stderr // Start the process. @@ -273,7 +272,7 @@ func (hook *Hook) ExecuteAsReadPipe(in io.Reader) (io.Reader, WaitFunc, int, err return nil, nil, HOOK_GENERIC_ERROR, fmt.Errorf("failed to configure stdout: %v", err) } cmd.Stdin = in - var stderr bytes.Buffer + var stderr strings.Builder cmd.Stderr = &stderr // Start the process. diff --git a/go/vt/key/destination.go b/go/vt/key/destination.go index 437e980f480..be95406cca7 100644 --- a/go/vt/key/destination.go +++ b/go/vt/key/destination.go @@ -17,7 +17,6 @@ limitations under the License. package key import ( - "bytes" "encoding/hex" "math/rand" "sort" @@ -48,7 +47,7 @@ type Destination interface { // DestinationsString returns a printed version of the destination array. func DestinationsString(destinations []Destination) string { - var buffer bytes.Buffer + var buffer strings.Builder buffer.WriteString("Destinations:") for i, d := range destinations { if i > 0 { @@ -177,7 +176,7 @@ func (d DestinationExactKeyRanges) Resolve(allShards []*topodatapb.ShardReferenc // String is part of the Destination interface. func (d DestinationExactKeyRanges) String() string { - var buffer bytes.Buffer + var buffer strings.Builder buffer.WriteString("DestinationExactKeyRanges(") for i, kr := range d { if i > 0 { @@ -246,7 +245,7 @@ func (d DestinationKeyRanges) Resolve(allShards []*topodatapb.ShardReference, ad // String is part of the Destination interface. func (d DestinationKeyRanges) String() string { - var buffer bytes.Buffer + var buffer strings.Builder buffer.WriteString("DestinationKeyRanges(") for i, kr := range d { if i > 0 { @@ -318,7 +317,7 @@ func (d DestinationKeyspaceIDs) Resolve(allShards []*topodatapb.ShardReference, // String is part of the Destination interface. func (d DestinationKeyspaceIDs) String() string { - var buffer bytes.Buffer + var buffer strings.Builder buffer.WriteString("DestinationKeyspaceIDs(") for i, ksid := range d { if i > 0 { diff --git a/go/vt/logutil/logger.go b/go/vt/logutil/logger.go index 524ca4db4d7..087c310011c 100644 --- a/go/vt/logutil/logger.go +++ b/go/vt/logutil/logger.go @@ -17,7 +17,6 @@ limitations under the License. package logutil import ( - "bytes" "fmt" "io" "runtime" @@ -57,7 +56,7 @@ type Logger interface { // EventToBuffer formats an individual Event into a buffer, without the // final '\n' -func EventToBuffer(event *logutilpb.Event, buf *bytes.Buffer) { +func EventToBuffer(event *logutilpb.Event, buf *strings.Builder) { // Avoid Fprintf, for speed. The format is so simple that we // can do it quickly by hand. It's worth about 3X. Fprintf is hard. @@ -98,8 +97,8 @@ func EventToBuffer(event *logutilpb.Event, buf *bytes.Buffer) { // EventString returns the line in one string func EventString(event *logutilpb.Event) string { - buf := new(bytes.Buffer) - EventToBuffer(event, buf) + var buf strings.Builder + EventToBuffer(event, &buf) return buf.String() } @@ -251,11 +250,11 @@ func NewMemoryLogger() *MemoryLogger { // String returns all the lines in one String, separated by '\n' func (ml *MemoryLogger) String() string { - buf := new(bytes.Buffer) + var buf strings.Builder ml.mu.Lock() defer ml.mu.Unlock() for _, event := range ml.Events { - EventToBuffer(event, buf) + EventToBuffer(event, &buf) buf.WriteByte('\n') } return buf.String() @@ -355,7 +354,7 @@ func (tl *TeeLogger) Printf(format string, v ...any) { const digits = "0123456789" // twoDigits adds a zero-prefixed two-digit integer to buf -func twoDigits(buf *bytes.Buffer, value int) { +func twoDigits(buf *strings.Builder, value int) { buf.WriteByte(digits[value/10]) buf.WriteByte(digits[value%10]) } @@ -363,7 +362,7 @@ func twoDigits(buf *bytes.Buffer, value int) { // nDigits adds an n-digit integer d to buf // padding with pad on the left. // It assumes d >= 0. -func nDigits(buf *bytes.Buffer, n, d int, pad byte) { +func nDigits(buf *strings.Builder, n, d int, pad byte) { tmp := make([]byte, n) j := n - 1 for ; j >= 0 && d > 0; j-- { @@ -377,7 +376,7 @@ func nDigits(buf *bytes.Buffer, n, d int, pad byte) { } // someDigits adds a zero-prefixed variable-width integer to buf -func someDigits(buf *bytes.Buffer, d int64) { +func someDigits(buf *strings.Builder, d int64) { // Print into the top, then copy down. tmp := make([]byte, 10) j := 10 diff --git a/go/vt/mysqlctl/mycnf_gen.go b/go/vt/mysqlctl/mycnf_gen.go index b29d152707f..dd0d6c81c81 100644 --- a/go/vt/mysqlctl/mycnf_gen.go +++ b/go/vt/mysqlctl/mycnf_gen.go @@ -19,11 +19,11 @@ limitations under the License. package mysqlctl import ( - "bytes" "crypto/rand" "fmt" "math/big" "path" + "strings" "text/template" "github.com/spf13/pflag" @@ -54,9 +54,7 @@ const ( innodbLogSubdir = "innodb/logs" ) -var ( - tabletDir string -) +var tabletDir string func init() { for _, cmd := range []string{"mysqlctl", "mysqlctld", "vtcombo", "vttablet", "vttestserver", "vtctld", "vtctldclient"} { @@ -149,8 +147,8 @@ func (cnf *Mycnf) fillMycnfTemplate(tmplSrc string) (string, error) { if err != nil { return "", err } - mycnfData := new(bytes.Buffer) - err = myTemplate.Execute(mycnfData, cnf) + var mycnfData strings.Builder + err = myTemplate.Execute(&mycnfData, cnf) if err != nil { return "", err } diff --git a/go/vt/mysqlctl/mysqld.go b/go/vt/mysqlctl/mysqld.go index ee872c214f4..b6a743cc120 100644 --- a/go/vt/mysqlctl/mysqld.go +++ b/go/vt/mysqlctl/mysqld.go @@ -780,7 +780,7 @@ func (mysqld *Mysqld) initConfig(cnf *Mycnf, outFile string) error { return err } - return os.WriteFile(outFile, []byte(configData), 0664) + return os.WriteFile(outFile, []byte(configData), 0o664) } func (mysqld *Mysqld) getMycnfTemplate() string { @@ -791,7 +791,7 @@ func (mysqld *Mysqld) getMycnfTemplate() string { } return string(data) // use only specified template } - myTemplateSource := new(bytes.Buffer) + var myTemplateSource strings.Builder myTemplateSource.WriteString("[mysqld]\n") myTemplateSource.WriteString(config.MycnfDefault) diff --git a/go/vt/schemadiff/schema.go b/go/vt/schemadiff/schema.go index 9180012676f..40848a96536 100644 --- a/go/vt/schemadiff/schema.go +++ b/go/vt/schemadiff/schema.go @@ -17,7 +17,6 @@ limitations under the License. package schemadiff import ( - "bytes" "errors" "fmt" "io" @@ -613,7 +612,7 @@ func (s *Schema) ToQueries() []string { // ToSQL returns a SQL blob with ordered sequence of queries which can be applied to create the schema func (s *Schema) ToSQL() string { - var buf bytes.Buffer + var buf strings.Builder for _, query := range s.ToQueries() { buf.WriteString(query) buf.WriteString(";\n") diff --git a/go/vt/servenv/status.go b/go/vt/servenv/status.go index ac912fd881e..7a8df5d5568 100644 --- a/go/vt/servenv/status.go +++ b/go/vt/servenv/status.go @@ -17,7 +17,6 @@ limitations under the License. package servenv import ( - "bytes" "fmt" "io" "net" @@ -256,7 +255,7 @@ func (sp *statusPage) statusHandler(w http.ResponseWriter, r *http.Request) { } func (sp *statusPage) reparse(sections []section) (*template.Template, error) { - var buf bytes.Buffer + var buf strings.Builder io.WriteString(&buf, `{{define "status"}}`) io.WriteString(&buf, statusHTML) @@ -301,7 +300,7 @@ func registerDebugBlockProfileRate() { runtime.SetBlockProfileRate(rate) log.Infof("Set block profile rate to: %d", rate) w.Header().Set("Content-Type", "text/plain") - w.Write([]byte(message)) + io.WriteString(w, message) }) } @@ -329,7 +328,7 @@ func registerDebugMutexProfileFraction() { runtime.SetMutexProfileFraction(fraction) log.Infof("Set mutex profiling fraction to: %d", fraction) w.Header().Set("Content-Type", "text/plain") - w.Write([]byte(message)) + io.WriteString(w, message) }) } diff --git a/go/vt/sqlparser/normalizer_test.go b/go/vt/sqlparser/normalizer_test.go index 7c8c5e7a963..9a92064d9b3 100644 --- a/go/vt/sqlparser/normalizer_test.go +++ b/go/vt/sqlparser/normalizer_test.go @@ -17,12 +17,12 @@ limitations under the License. package sqlparser import ( - "bytes" "fmt" "math/rand" "reflect" "regexp" "strconv" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -625,7 +625,7 @@ values func BenchmarkNormalizeTPCCInsert(b *testing.B) { generateInsert := func(rows int) string { - var query bytes.Buffer + var query strings.Builder query.WriteString("INSERT IGNORE INTO customer0 (c_id, c_d_id, c_w_id, c_first, c_middle, c_last, c_street_1, c_street_2, c_city, c_state, c_zip, c_phone, c_since, c_credit, c_credit_lim, c_discount, c_balance, c_ytd_payment, c_payment_cnt, c_delivery_cnt, c_data) values ") for i := 0; i < rows; i++ { fmt.Fprintf(&query, "(%d, %d, %d, '%s','OE','%s','%s', '%s', '%s', '%s', '%s','%s',NOW(),'%s',50000,%f,-10,10,1,0,'%s' )", diff --git a/go/vt/sqlparser/parse_next_test.go b/go/vt/sqlparser/parse_next_test.go index 2e55fbb8a9a..756bf4fb3d0 100644 --- a/go/vt/sqlparser/parse_next_test.go +++ b/go/vt/sqlparser/parse_next_test.go @@ -17,7 +17,6 @@ limitations under the License. package sqlparser import ( - "bytes" "io" "strings" "testing" @@ -29,7 +28,7 @@ import ( // TestParseNextValid concatenates all the valid SQL test cases and check it can read // them as one long string. func TestParseNextValid(t *testing.T) { - var sql bytes.Buffer + var sql strings.Builder for _, tcase := range validSQL { sql.WriteString(strings.TrimSuffix(tcase.input, ";")) sql.WriteRune(';') diff --git a/go/vt/sqlparser/parse_test.go b/go/vt/sqlparser/parse_test.go index a6c9d9ccf88..4fe2cd8f247 100644 --- a/go/vt/sqlparser/parse_test.go +++ b/go/vt/sqlparser/parse_test.go @@ -18,7 +18,6 @@ package sqlparser import ( "bufio" - "bytes" "compress/gzip" "fmt" "io" @@ -6130,7 +6129,7 @@ func BenchmarkParseStress(b *testing.B) { for i, sql := range []string{sql1, sql2} { b.Run(fmt.Sprintf("sql%d", i), func(b *testing.B) { - var buf bytes.Buffer + var buf strings.Builder buf.WriteString(sql) querySQL := buf.String() b.ReportAllocs() @@ -6155,7 +6154,7 @@ func BenchmarkParse3(b *testing.B) { // Size of value is 1/10 size of query. Then we add // 10 such values to the where clause. - var baseval bytes.Buffer + var baseval strings.Builder for i := 0; i < benchQuerySize/100; i++ { // Add an escape character: This will force the upcoming // tokenizer improvement to still create a copy of the string. @@ -6167,7 +6166,7 @@ func BenchmarkParse3(b *testing.B) { } } - var buf bytes.Buffer + var buf strings.Builder buf.WriteString("select a from t1 where v = 1") for i := 0; i < 10; i++ { fmt.Fprintf(&buf, " and v%d = \"%d%s\"", i, i, baseval.String()) diff --git a/go/vt/throttler/result.go b/go/vt/throttler/result.go index 179711116a3..0976a180877 100644 --- a/go/vt/throttler/result.go +++ b/go/vt/throttler/result.go @@ -17,8 +17,8 @@ limitations under the License. package throttler import ( - "bytes" "fmt" + "strings" "sync" "text/template" "time" @@ -81,7 +81,7 @@ type result struct { } func (r result) String() string { - var b bytes.Buffer + var b strings.Builder if err := resultStringTemplate.Execute(&b, r); err != nil { panic(fmt.Sprintf("failed to Execute() template: %v", err)) } diff --git a/go/vt/vtctl/workflow/server.go b/go/vt/vtctl/workflow/server.go index 6927b56b89d..21723504019 100644 --- a/go/vt/vtctl/workflow/server.go +++ b/go/vt/vtctl/workflow/server.go @@ -17,7 +17,6 @@ limitations under the License. package workflow import ( - "bytes" "context" "errors" "fmt" @@ -929,7 +928,6 @@ ORDER BY func (s *Server) getWorkflowState(ctx context.Context, targetKeyspace, workflowName string) (*trafficSwitcher, *State, error) { ts, err := s.buildTrafficSwitcher(ctx, targetKeyspace, workflowName) - if err != nil { log.Errorf("buildTrafficSwitcher failed: %v", err) return nil, nil, err @@ -973,7 +971,6 @@ func (s *Server) getWorkflowState(ctx context.Context, targetKeyspace, workflowN // We assume a consistent state, so only choose routing rule for one table. if len(ts.Tables()) == 0 { return nil, nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "no tables in workflow %s.%s", targetKeyspace, workflowName) - } table := ts.Tables()[0] @@ -1263,8 +1260,8 @@ func (s *Server) MoveTablesCreate(ctx context.Context, req *vtctldatapb.MoveTabl } func (s *Server) moveTablesCreate(ctx context.Context, req *vtctldatapb.MoveTablesCreateRequest, - workflowType binlogdatapb.VReplicationWorkflowType) (res *vtctldatapb.WorkflowStatusResponse, err error) { - + workflowType binlogdatapb.VReplicationWorkflowType, +) (res *vtctldatapb.WorkflowStatusResponse, err error) { span, ctx := trace.NewSpan(ctx, "workflow.Server.MoveTablesCreate") defer span.Finish() @@ -1276,7 +1273,7 @@ func (s *Server) moveTablesCreate(ctx context.Context, req *vtctldatapb.MoveTabl sourceKeyspace := req.SourceKeyspace targetKeyspace := req.TargetKeyspace - //FIXME validate tableSpecs, allTables, excludeTables + // FIXME validate tableSpecs, allTables, excludeTables var ( tables = req.IncludeTables externalTopo *topo.Server @@ -2028,7 +2025,7 @@ func (s *Server) GetCopyProgress(ctx context.Context, ts *trafficSwitcher, state sourceTableSizes[table] = 0 } - var getTableMetrics = func(tablet *topodatapb.Tablet, query string, rowCounts *map[string]int64, tableSizes *map[string]int64) error { + getTableMetrics := func(tablet *topodatapb.Tablet, query string, rowCounts *map[string]int64, tableSizes *map[string]int64) error { p3qr, err := s.tmc.ExecuteFetchAsDba(ctx, tablet, true, &tabletmanagerdatapb.ExecuteFetchAsDbaRequest{ Query: []byte(query), MaxRows: uint64(len(tables)), @@ -2762,7 +2759,8 @@ func (s *Server) DeleteShard(ctx context.Context, keyspace, shard string, recurs // updateShardRecords updates the shard records based on 'from' or 'to' direction. func (s *Server) updateShardRecords(ctx context.Context, keyspace string, shards []*topo.ShardInfo, cells []string, - servedType topodatapb.TabletType, isFrom bool, clearSourceShards bool, logger logutil.Logger) (err error) { + servedType topodatapb.TabletType, isFrom bool, clearSourceShards bool, logger logutil.Logger, +) (err error) { return topotools.UpdateShardRecords(ctx, s.ts, s.tmc, keyspace, shards, cells, servedType, isFrom, clearSourceShards, logger) } @@ -2977,7 +2975,7 @@ func (s *Server) switchReads(ctx context.Context, req *vtctldatapb.WorkflowSwitc return handleError("invalid request", vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requesting reversal of SwitchReads for RDONLYs but RDONLY reads have not been switched")) } } - var cells = req.Cells + cells := req.Cells // If no cells were provided in the command then use the value from the workflow. if len(cells) == 0 && ts.optCells != "" { cells = strings.Split(strings.TrimSpace(ts.optCells), ",") @@ -3048,8 +3046,8 @@ func (s *Server) switchReads(ctx context.Context, req *vtctldatapb.WorkflowSwitc // switchWrites is a generic way of migrating write traffic for a workflow. func (s *Server) switchWrites(ctx context.Context, req *vtctldatapb.WorkflowSwitchTrafficRequest, ts *trafficSwitcher, timeout time.Duration, - cancel bool) (journalID int64, dryRunResults *[]string, err error) { - + cancel bool, +) (journalID int64, dryRunResults *[]string, err error) { var sw iswitcher if req.DryRun { sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()} @@ -3402,8 +3400,8 @@ func (s *Server) applySQLShard(ctx context.Context, tabletInfo *topo.TabletInfo, // fillStringTemplate returns the string template filled. func fillStringTemplate(tmpl string, vars any) (string, error) { myTemplate := template.Must(template.New("").Parse(tmpl)) - data := new(bytes.Buffer) - if err := myTemplate.Execute(data, vars); err != nil { + var data strings.Builder + if err := myTemplate.Execute(&data, vars); err != nil { return "", err } return data.String(), nil diff --git a/go/vt/vtexplain/vtexplain.go b/go/vt/vtexplain/vtexplain.go index 55e76606e08..b15d5d2af3a 100644 --- a/go/vt/vtexplain/vtexplain.go +++ b/go/vt/vtexplain/vtexplain.go @@ -20,7 +20,6 @@ limitations under the License. package vtexplain import ( - "bytes" "context" "fmt" "sort" @@ -43,9 +42,7 @@ import ( vtgatepb "vitess.io/vitess/go/vt/proto/vtgate" ) -var ( - batchInterval = 10 * time.Millisecond -) +var batchInterval = 10 * time.Millisecond func init() { servenv.OnParseFor("vtexplain", func(fs *pflag.FlagSet) { @@ -154,10 +151,11 @@ type ( func (tq *TabletQuery) MarshalJSON() ([]byte, error) { // Convert Bindvars to strings for nicer output bindVars := make(map[string]string) + var buf strings.Builder for k, v := range tq.BindVars { - var b strings.Builder - sqlparser.EncodeValue(&b, v) - bindVars[k] = b.String() + buf.Reset() + sqlparser.EncodeValue(&buf, v) + bindVars[k] = buf.String() } return jsonutil.MarshalNoEscape(&struct { @@ -337,7 +335,7 @@ func (vte *VTExplain) explain(sql string) (*Explain, error) { // ExplainsAsText returns a text representation of the explains in logical time // order func (vte *VTExplain) ExplainsAsText(explains []*Explain) (string, error) { - var b bytes.Buffer + var b strings.Builder for _, explain := range explains { fmt.Fprintf(&b, "----------------------------------------------------------------------\n") fmt.Fprintf(&b, "%s\n\n", explain.SQL) diff --git a/go/vt/vtgate/engine/set.go b/go/vt/vtgate/engine/set.go index df56fc04ed2..9e9500d1ca8 100644 --- a/go/vt/vtgate/engine/set.go +++ b/go/vt/vtgate/engine/set.go @@ -17,7 +17,6 @@ limitations under the License. package engine import ( - "bytes" "context" "encoding/json" "fmt" @@ -181,7 +180,6 @@ func (u *UserDefinedVariable) MarshalJSON() ([]byte, error) { Name: u.Name, Expr: sqlparser.String(u.Expr), }) - } // VariableName implements the SetOp interface method. @@ -209,7 +207,6 @@ func (svi *SysVarIgnore) MarshalJSON() ([]byte, error) { Type: "SysVarIgnore", SysVarIgnore: *svi, }) - } // VariableName implements the SetOp interface method. @@ -234,7 +231,6 @@ func (svci *SysVarCheckAndIgnore) MarshalJSON() ([]byte, error) { Type: "SysVarCheckAndIgnore", SysVarCheckAndIgnore: *svci, }) - } // VariableName implements the SetOp interface method @@ -278,7 +274,6 @@ func (svs *SysVarReservedConn) MarshalJSON() ([]byte, error) { Type: "SysVarSet", SysVarReservedConn: *svs, }) - } // VariableName implements the SetOp interface method @@ -363,8 +358,8 @@ func (svs *SysVarReservedConn) checkAndUpdateSysVar(ctx context.Context, vcursor } else { value = qr.Rows[0][0] } - buf := new(bytes.Buffer) - value.EncodeSQL(buf) + var buf strings.Builder + value.EncodeSQL(&buf) s := buf.String() vcursor.Session().SetSysVar(svs.Name, s) diff --git a/go/vt/vtgate/vindexes/consistent_lookup.go b/go/vt/vtgate/vindexes/consistent_lookup.go index d73631cc6ca..fb5eb5dfb0a 100644 --- a/go/vt/vtgate/vindexes/consistent_lookup.go +++ b/go/vt/vtgate/vindexes/consistent_lookup.go @@ -21,6 +21,7 @@ import ( "context" "encoding/json" "fmt" + "strings" "vitess.io/vitess/go/mysql/sqlerror" "vitess.io/vitess/go/sqltypes" @@ -433,7 +434,7 @@ func (lu *clCommon) MarshalJSON() ([]byte, error) { } func (lu *clCommon) generateLockLookup() string { - var buf bytes.Buffer + var buf strings.Builder fmt.Fprintf(&buf, "select %s from %s", lu.lkp.To, lu.lkp.Table) lu.addWhere(&buf, lu.lkp.FromColumns) fmt.Fprintf(&buf, " for update") @@ -441,7 +442,7 @@ func (lu *clCommon) generateLockLookup() string { } func (lu *clCommon) generateLockOwner() string { - var buf bytes.Buffer + var buf strings.Builder fmt.Fprintf(&buf, "select %s from %s", lu.ownerColumns[0], lu.ownerTable) lu.addWhere(&buf, lu.ownerColumns) // We can lock in share mode because we only want to check @@ -452,7 +453,7 @@ func (lu *clCommon) generateLockOwner() string { } func (lu *clCommon) generateInsertLookup() string { - var buf bytes.Buffer + var buf strings.Builder fmt.Fprintf(&buf, "insert into %s(", lu.lkp.Table) for _, col := range lu.lkp.FromColumns { fmt.Fprintf(&buf, "%s, ", col) @@ -466,13 +467,13 @@ func (lu *clCommon) generateInsertLookup() string { } func (lu *clCommon) generateUpdateLookup() string { - var buf bytes.Buffer + var buf strings.Builder fmt.Fprintf(&buf, "update %s set %s=:%s", lu.lkp.Table, lu.lkp.To, lu.lkp.To) lu.addWhere(&buf, lu.lkp.FromColumns) return buf.String() } -func (lu *clCommon) addWhere(buf *bytes.Buffer, cols []string) { +func (lu *clCommon) addWhere(buf *strings.Builder, cols []string) { buf.WriteString(" where ") for colIdx, column := range cols { if colIdx != 0 { diff --git a/go/vt/vtgate/vindexes/lookup_internal.go b/go/vt/vtgate/vindexes/lookup_internal.go index 673b3fcb64b..dac6ea8c27a 100644 --- a/go/vt/vtgate/vindexes/lookup_internal.go +++ b/go/vt/vtgate/vindexes/lookup_internal.go @@ -312,16 +312,16 @@ nextRow: if lkp.MultiShardAutocommit { insStmt = "insert /*vt+ MULTI_SHARD_AUTOCOMMIT=1 */" } - buf := new(bytes.Buffer) + var buf strings.Builder if ignoreMode { - fmt.Fprintf(buf, "%s ignore into %s(", insStmt, lkp.Table) + fmt.Fprintf(&buf, "%s ignore into %s(", insStmt, lkp.Table) } else { - fmt.Fprintf(buf, "%s into %s(", insStmt, lkp.Table) + fmt.Fprintf(&buf, "%s into %s(", insStmt, lkp.Table) } for _, col := range lkp.FromColumns { - fmt.Fprintf(buf, "%s, ", col) + fmt.Fprintf(&buf, "%s, ", col) } - fmt.Fprintf(buf, "%s) values(", lkp.To) + fmt.Fprintf(&buf, "%s) values(", lkp.To) bindVars := make(map[string]*querypb.BindVariable, 2*len(trimmedRowsCols)) for rowIdx := range trimmedToValues { @@ -340,11 +340,11 @@ nextRow: } if lkp.Upsert { - fmt.Fprintf(buf, " on duplicate key update ") + fmt.Fprintf(&buf, " on duplicate key update ") for _, col := range lkp.FromColumns { - fmt.Fprintf(buf, "%s=values(%s), ", col, col) + fmt.Fprintf(&buf, "%s=values(%s), ", col, col) } - fmt.Fprintf(buf, "%s=values(%s)", lkp.To, lkp.To) + fmt.Fprintf(&buf, "%s=values(%s)", lkp.To, lkp.To) } if _, err := vcursor.Execute(ctx, "VindexCreate", buf.String(), bindVars, true /* rollbackOnError */, co); err != nil { @@ -405,7 +405,7 @@ func (lkp *lookupInternal) Update(ctx context.Context, vcursor VCursor, oldValue } func (lkp *lookupInternal) initDelStmt() string { - var delBuffer bytes.Buffer + var delBuffer strings.Builder fmt.Fprintf(&delBuffer, "delete from %s where ", lkp.Table) for colIdx, column := range lkp.FromColumns { if colIdx != 0 { diff --git a/go/vt/vtorc/inst/instance_dao.go b/go/vt/vtorc/inst/instance_dao.go index 211ddce69b1..01b8a750f57 100644 --- a/go/vt/vtorc/inst/instance_dao.go +++ b/go/vt/vtorc/inst/instance_dao.go @@ -17,7 +17,6 @@ package inst import ( - "bytes" "errors" "fmt" "regexp" @@ -52,20 +51,26 @@ const ( backendDBConcurrency = 20 ) -var instanceReadChan = make(chan bool, backendDBConcurrency) -var instanceWriteChan = make(chan bool, backendDBConcurrency) +var ( + instanceReadChan = make(chan bool, backendDBConcurrency) + instanceWriteChan = make(chan bool, backendDBConcurrency) +) var forgetAliases *cache.Cache -var accessDeniedCounter = metrics.NewCounter() -var readTopologyInstanceCounter = metrics.NewCounter() -var readInstanceCounter = metrics.NewCounter() -var writeInstanceCounter = metrics.NewCounter() -var backendWrites = collection.CreateOrReturnCollection("BACKEND_WRITES") -var writeBufferLatency = stopwatch.NewNamedStopwatch() +var ( + accessDeniedCounter = metrics.NewCounter() + readTopologyInstanceCounter = metrics.NewCounter() + readInstanceCounter = metrics.NewCounter() + writeInstanceCounter = metrics.NewCounter() + backendWrites = collection.CreateOrReturnCollection("BACKEND_WRITES") + writeBufferLatency = stopwatch.NewNamedStopwatch() +) -var emptyQuotesRegexp = regexp.MustCompile(`^""$`) -var cacheInitializationCompleted atomic.Bool +var ( + emptyQuotesRegexp = regexp.MustCompile(`^""$`) + cacheInitializationCompleted atomic.Bool +) func init() { _ = metrics.Register("instance.access_denied", accessDeniedCounter) @@ -749,12 +754,10 @@ func ReadOutdatedInstanceKeys() ([]string, error) { // We don;t return an error because we want to keep filling the outdated instances list. return nil }) - if err != nil { log.Error(err) } return res, err - } func mkInsertOdku(table string, columns []string, values []string, nrRows int, insertIgnore bool) (string, error) { @@ -768,21 +771,21 @@ func mkInsertOdku(table string, columns []string, values []string, nrRows int, i return "", errors.New("number of values must be equal to number of columns") } - var q bytes.Buffer + var q strings.Builder var ignore string if insertIgnore { ignore = "ignore" } - var valRow = fmt.Sprintf("(%s)", strings.Join(values, ", ")) - var val bytes.Buffer + valRow := fmt.Sprintf("(%s)", strings.Join(values, ", ")) + var val strings.Builder val.WriteString(valRow) for i := 1; i < nrRows; i++ { val.WriteString(",\n ") // indent VALUES, see below val.WriteString(valRow) } - var col = strings.Join(columns, ", ") - var odku bytes.Buffer + col := strings.Join(columns, ", ") + var odku strings.Builder odku.WriteString(fmt.Sprintf("%s=VALUES(%s)", columns[0], columns[0])) for _, c := range columns[1:] { odku.WriteString(", ") @@ -810,7 +813,7 @@ func mkInsertOdkuForInstances(instances []*Instance, instanceWasActuallyFound bo if !instanceWasActuallyFound { insertIgnore = true } - var columns = []string{ + columns := []string{ "alias", "hostname", "port", @@ -876,7 +879,7 @@ func mkInsertOdkuForInstances(instances []*Instance, instanceWasActuallyFound bo "last_discovery_latency", } - var values = make([]string, len(columns)) + values := make([]string, len(columns)) for i := range columns { values[i] = "?" } diff --git a/go/vt/vttablet/sysloglogger/sysloglogger.go b/go/vt/vttablet/sysloglogger/sysloglogger.go index e56d47bd902..87601884d5c 100644 --- a/go/vt/vttablet/sysloglogger/sysloglogger.go +++ b/go/vt/vttablet/sysloglogger/sysloglogger.go @@ -18,8 +18,8 @@ limitations under the License. package sysloglogger import ( - "bytes" "log/syslog" + "strings" "github.com/spf13/pflag" @@ -76,8 +76,10 @@ func run() { } formatParams := map[string][]string{"full": {}} + + var b strings.Builder for stats := range ch { - var b bytes.Buffer + b.Reset() if err := stats.Logf(&b, formatParams); err != nil { log.Errorf("Error formatting logStats: %v", err) continue diff --git a/go/vt/vttablet/tabletserver/tabletenv/logstats_test.go b/go/vt/vttablet/tabletserver/tabletenv/logstats_test.go index 84de50aae74..51e056687b5 100644 --- a/go/vt/vttablet/tabletserver/tabletenv/logstats_test.go +++ b/go/vt/vttablet/tabletserver/tabletenv/logstats_test.go @@ -17,7 +17,6 @@ limitations under the License. package tabletenv import ( - "bytes" "context" "encoding/json" "errors" @@ -54,7 +53,7 @@ func TestLogStats(t *testing.T) { } func testFormat(stats *LogStats, params url.Values) string { - var b bytes.Buffer + var b strings.Builder stats.Logf(&b, params) return b.String() } @@ -183,7 +182,6 @@ func TestLogStatsFilter(t *testing.T) { if got != want { t.Errorf("logstats format: got:\n%q\nwant:\n%q\n", got, want) } - } func TestLogStatsFormatQuerySources(t *testing.T) { diff --git a/go/vt/vttest/local_cluster.go b/go/vt/vttest/local_cluster.go index 9d84cb7fceb..6138508aea6 100644 --- a/go/vt/vttest/local_cluster.go +++ b/go/vt/vttest/local_cluster.go @@ -18,7 +18,6 @@ package vttest import ( "bufio" - "bytes" "context" "encoding/json" "fmt" @@ -173,12 +172,12 @@ func (cfg *Config) InitSchemas(keyspace, schema string, vschema *vschemapb.Keysp // Write the schema if set. if schema != "" { ksDir := path.Join(schemaDir, keyspace) - err := os.Mkdir(ksDir, os.ModeDir|0775) + err := os.Mkdir(ksDir, os.ModeDir|0o775) if err != nil { return err } fileName := path.Join(ksDir, "schema.sql") - err = os.WriteFile(fileName, []byte(schema), 0666) + err = os.WriteFile(fileName, []byte(schema), 0o666) if err != nil { return err } @@ -191,7 +190,7 @@ func (cfg *Config) InitSchemas(keyspace, schema string, vschema *vschemapb.Keysp if err != nil { return err } - if err := os.WriteFile(vschemaFilePath, vschemaJSON, 0644); err != nil { + if err := os.WriteFile(vschemaFilePath, vschemaJSON, 0o644); err != nil { return err } } @@ -554,6 +553,7 @@ func (db *LocalCluster) createVTSchema() error { } return nil } + func (db *LocalCluster) createDatabases() error { log.Info("Creating databases in cluster...") @@ -697,7 +697,7 @@ func dirExist(dir string) bool { // statements in the SQL file. func LoadSQLFile(filename, sourceroot string) ([]string, error) { var ( - cmd bytes.Buffer + cmd strings.Builder sql []string inSQ bool inDQ bool diff --git a/go/vt/wrangler/schema.go b/go/vt/wrangler/schema.go index 84bc078f240..e6c1fbc25d9 100644 --- a/go/vt/wrangler/schema.go +++ b/go/vt/wrangler/schema.go @@ -17,9 +17,9 @@ limitations under the License. package wrangler import ( - "bytes" "context" "fmt" + "strings" "sync" "text/template" "time" @@ -307,8 +307,8 @@ func (wr *Wrangler) applySQLShard(ctx context.Context, tabletInfo *topo.TabletIn // fillStringTemplate returns the string template filled func fillStringTemplate(tmpl string, vars any) (string, error) { myTemplate := template.Must(template.New("").Parse(tmpl)) - data := new(bytes.Buffer) - if err := myTemplate.Execute(data, vars); err != nil { + var data strings.Builder + if err := myTemplate.Execute(&data, vars); err != nil { return "", err } return data.String(), nil diff --git a/go/vt/zkctl/zkconf.go b/go/vt/zkctl/zkconf.go index 15a912231ff..7361408c3fc 100644 --- a/go/vt/zkctl/zkconf.go +++ b/go/vt/zkctl/zkconf.go @@ -24,7 +24,6 @@ limitations under the License. package zkctl import ( - "bytes" "fmt" "os" "path" @@ -94,16 +93,16 @@ func (cnf *ZkConfig) MyidFile() string { } func (cnf *ZkConfig) WriteMyid() error { - return os.WriteFile(cnf.MyidFile(), []byte(fmt.Sprintf("%v", cnf.ServerId)), 0664) + return os.WriteFile(cnf.MyidFile(), []byte(fmt.Sprintf("%v", cnf.ServerId)), 0o664) } /* Search for first existing file in cnfFiles and subsitute in the right values. */ func MakeZooCfg(cnfFiles []string, cnf *ZkConfig, header string) (string, error) { - myTemplateSource := new(bytes.Buffer) + var myTemplateSource strings.Builder for _, line := range strings.Split(header, "\n") { - fmt.Fprintf(myTemplateSource, "## %v\n", strings.TrimSpace(line)) + fmt.Fprintf(&myTemplateSource, "## %v\n", strings.TrimSpace(line)) } var dataErr error for _, path := range cnfFiles { @@ -127,8 +126,8 @@ func MakeZooCfg(cnfFiles []string, cnf *ZkConfig, header string) (string, error) if err != nil { return "", err } - cnfData := new(bytes.Buffer) - err = myTemplate.Execute(cnfData, cnf) + var cnfData strings.Builder + err = myTemplate.Execute(&cnfData, cnf) if err != nil { return "", err } @@ -161,8 +160,10 @@ func MakeZkConfigFromString(cmdLine string, myID uint32) *ZkConfig { } myID = myID % 1000 - zkServer := zkServerAddr{ServerId: uint32(serverID), ClientPort: 2181, - LeaderPort: 2888, ElectionPort: 3888} + zkServer := zkServerAddr{ + ServerId: uint32(serverID), ClientPort: 2181, + LeaderPort: 2888, ElectionPort: 3888, + } switch len(zkAddrParts) { case 4: zkServer.ClientPort, _ = strconv.Atoi(zkAddrParts[3])