Simplified code in various places (#6176)

All these changes should have no side-effects or change behavior:

- Use bytes.Buffer's String() instead of a conversion
- Use time.Since and time.Until where fitting
- Drop unnecessary returns and assignment
This commit is contained in:
Christian Muehlhaeuser 2019-07-20 15:37:19 +02:00 committed by Matt Keeler
parent 358c1a6e7a
commit 2602f6907e
18 changed files with 18 additions and 26 deletions

View File

@ -141,7 +141,7 @@ func (s *HTTPServer) AgentReload(resp http.ResponseWriter, req *http.Request) (i
}
// Trigger the reload
errCh := make(chan error, 0)
errCh := make(chan error)
select {
case <-s.agent.shutdownCh:
return nil, fmt.Errorf("Agent was shutdown before reload could be completed")

View File

@ -532,7 +532,7 @@ func TestAgent_Service(t *testing.T) {
}
start := time.Now()
obj, err := a.srv.AgentService(resp, req)
elapsed := time.Now().Sub(start)
elapsed := time.Since(start)
if tt.wantErr != "" {
require.Error(err)
@ -5298,7 +5298,7 @@ func TestAgentConnectProxyConfig_Blocking(t *testing.T) {
}
start := time.Now()
obj, err := a.srv.AgentConnectProxyConfig(resp, req)
elapsed := time.Now().Sub(start)
elapsed := time.Since(start)
if tt.wantErr {
require.Error(err)

View File

@ -703,7 +703,7 @@ func (c *Cache) runExpiryLoop() {
c.entriesLock.RLock()
if len(c.entriesExpiryHeap.Entries) > 0 {
entry = c.entriesExpiryHeap.Entries[0]
expiryTimer = time.NewTimer(entry.Expires.Sub(time.Now()))
expiryTimer = time.NewTimer(time.Until(entry.Expires))
expiryCh = expiryTimer.C
}
c.entriesLock.RUnlock()

View File

@ -151,7 +151,7 @@ RETRY_ONCE:
// Use empty map instead of nil
if out.Services == nil {
out.Services = make(structs.Services, 0)
out.Services = make(structs.Services)
}
metrics.IncrCounterWithLabels([]string{"client", "api", "success", "catalog_services"}, 1,
[]metrics.Label{{Name: "node", Value: s.nodeName()}})

View File

@ -178,7 +178,7 @@ func TestConsulCAProvider_SignLeaf(t *testing.T) {
require.Equal(parsed.SerialNumber.Uint64(), uint64(2))
// Ensure the cert is valid now and expires within the correct limit.
require.True(parsed.NotAfter.Sub(time.Now()) < 3*24*time.Hour)
require.True(time.Until(parsed.NotAfter) < 3*24*time.Hour)
require.True(parsed.NotBefore.Before(time.Now()))
}

View File

@ -186,7 +186,7 @@ func TestVaultCAProvider_SignLeaf(t *testing.T) {
require.NotEqual(firstSerial, parsed.SerialNumber.Uint64())
// Ensure the cert is valid now and expires within the correct limit.
require.True(parsed.NotAfter.Sub(time.Now()) < time.Hour)
require.True(time.Until(parsed.NotAfter) < time.Hour)
require.True(parsed.NotBefore.Before(time.Now()))
}
}

View File

@ -316,7 +316,7 @@ func (r *aclRoleReplicator) FetchUpdated(srv *Server, updates []string) (int, er
delete(keep, role.ID)
}
missing := make([]string, 0, len(keep))
for id, _ := range keep {
for id := range keep {
missing = append(missing, id)
}
return 0, fmt.Errorf("role replication trying to replicated uncached roles with IDs: %v", missing)

View File

@ -596,11 +596,7 @@ key "zip" {
t.Fatalf("err: %v", err)
}
actualKeys = []string{}
for _, key := range keyList.Keys {
actualKeys = append(actualKeys, key)
}
actualKeys = keyList.Keys
verify.Values(t, "", actualKeys, expectedKeys)

View File

@ -1192,7 +1192,7 @@ func (s *Server) pruneCARoots() error {
var newRoots structs.CARoots
for _, r := range roots {
if !r.Active && !r.RotatedOutAt.IsZero() && time.Now().Sub(r.RotatedOutAt) > common.LeafCertTTL*2 {
if !r.Active && !r.RotatedOutAt.IsZero() && time.Since(r.RotatedOutAt) > common.LeafCertTTL*2 {
s.logger.Printf("[INFO] connect: pruning old unused root CA (ID: %s)", r.ID)
continue
}

View File

@ -51,8 +51,7 @@ func (sl *ServerLookup) ServerAddr(id raft.ServerID) (raft.ServerAddress, error)
func (sl *ServerLookup) Server(addr raft.ServerAddress) *metadata.Server {
sl.lock.RLock()
defer sl.lock.RUnlock()
svr, _ := sl.addressToServer[addr]
return svr
return sl.addressToServer[addr]
}
func (sl *ServerLookup) Servers() []*metadata.Server {

View File

@ -820,7 +820,6 @@ func TestServer_BadExpect(t *testing.T) {
type fakeGlobalResp struct{}
func (r *fakeGlobalResp) Add(interface{}) {
return
}
func (r *fakeGlobalResp) New() interface{} {

View File

@ -3824,11 +3824,11 @@ func stripIrrelevantTokenFields(token *structs.ACLToken) *structs.ACLToken {
// When comparing the tokens disregard the policy link names. This
// data is not cleanly updated in a variety of scenarios and should not
// be relied upon.
for i, _ := range tokenCopy.Policies {
for i := range tokenCopy.Policies {
tokenCopy.Policies[i].Name = ""
}
// Also do the same for Role links.
for i, _ := range tokenCopy.Roles {
for i := range tokenCopy.Roles {
tokenCopy.Roles[i].Name = ""
}
// The raft indexes won't match either because the requester will not

View File

@ -293,7 +293,7 @@ func (s *HTTPServer) handler(enableDebug bool) http.Handler {
mux.HandleFunc("/", s.Index)
for pattern, fn := range endpoints {
thisFn := fn
methods, _ := allowedMethods[pattern]
methods := allowedMethods[pattern]
bound := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
return thisFn(s, resp, req)
}

View File

@ -342,8 +342,6 @@ func (m *Manager) RebalanceServers() {
// continue to use the existing connection until the next
// rebalance occurs.
}
return
}
// reconcileServerList returns true when the first server in serverList

View File

@ -60,7 +60,7 @@ func TestUiIndex(t *testing.T) {
// Verify the body
out := bytes.NewBuffer(nil)
io.Copy(out, resp.Body)
if string(out.Bytes()) != "test" {
if out.String() != "test" {
t.Fatalf("bad: %s", out.Bytes())
}
}

View File

@ -302,7 +302,7 @@ func (c *cmd) captureStatic() error {
var errors error
// Collect the named outputs here
outputs := make(map[string]interface{}, 0)
outputs := make(map[string]interface{})
// Capture host information
if c.configuredTarget("host") {

View File

@ -225,7 +225,7 @@ func (c *TelemetryConfig) MergeDefaults(defaults *TelemetryConfig) {
continue
}
case reflect.Bool:
if f.Bool() != false {
if f.Bool() {
continue
}
default:

View File

@ -110,7 +110,7 @@ func dedup(a []string) string {
delete(m, s)
}
}
return string(b.Bytes())
return b.String()
}
func run(r Retryer, t Failer, f func(r *R)) {