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 ef257b084d
commit 7753b97cc7
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 // Trigger the reload
errCh := make(chan error, 0) errCh := make(chan error)
select { select {
case <-s.agent.shutdownCh: case <-s.agent.shutdownCh:
return nil, fmt.Errorf("Agent was shutdown before reload could be completed") 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() start := time.Now()
obj, err := a.srv.AgentService(resp, req) obj, err := a.srv.AgentService(resp, req)
elapsed := time.Now().Sub(start) elapsed := time.Since(start)
if tt.wantErr != "" { if tt.wantErr != "" {
require.Error(err) require.Error(err)
@ -5298,7 +5298,7 @@ func TestAgentConnectProxyConfig_Blocking(t *testing.T) {
} }
start := time.Now() start := time.Now()
obj, err := a.srv.AgentConnectProxyConfig(resp, req) obj, err := a.srv.AgentConnectProxyConfig(resp, req)
elapsed := time.Now().Sub(start) elapsed := time.Since(start)
if tt.wantErr { if tt.wantErr {
require.Error(err) require.Error(err)

View File

@ -703,7 +703,7 @@ func (c *Cache) runExpiryLoop() {
c.entriesLock.RLock() c.entriesLock.RLock()
if len(c.entriesExpiryHeap.Entries) > 0 { if len(c.entriesExpiryHeap.Entries) > 0 {
entry = 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 expiryCh = expiryTimer.C
} }
c.entriesLock.RUnlock() c.entriesLock.RUnlock()

View File

@ -151,7 +151,7 @@ RETRY_ONCE:
// Use empty map instead of nil // Use empty map instead of nil
if out.Services == 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.IncrCounterWithLabels([]string{"client", "api", "success", "catalog_services"}, 1,
[]metrics.Label{{Name: "node", Value: s.nodeName()}}) []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)) require.Equal(parsed.SerialNumber.Uint64(), uint64(2))
// Ensure the cert is valid now and expires within the correct limit. // 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())) 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()) require.NotEqual(firstSerial, parsed.SerialNumber.Uint64())
// Ensure the cert is valid now and expires within the correct limit. // 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())) 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) delete(keep, role.ID)
} }
missing := make([]string, 0, len(keep)) missing := make([]string, 0, len(keep))
for id, _ := range keep { for id := range keep {
missing = append(missing, id) missing = append(missing, id)
} }
return 0, fmt.Errorf("role replication trying to replicated uncached roles with IDs: %v", missing) 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) t.Fatalf("err: %v", err)
} }
actualKeys = []string{} actualKeys = keyList.Keys
for _, key := range keyList.Keys {
actualKeys = append(actualKeys, key)
}
verify.Values(t, "", actualKeys, expectedKeys) verify.Values(t, "", actualKeys, expectedKeys)

View File

@ -1192,7 +1192,7 @@ func (s *Server) pruneCARoots() error {
var newRoots structs.CARoots var newRoots structs.CARoots
for _, r := range roots { 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) s.logger.Printf("[INFO] connect: pruning old unused root CA (ID: %s)", r.ID)
continue 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 { func (sl *ServerLookup) Server(addr raft.ServerAddress) *metadata.Server {
sl.lock.RLock() sl.lock.RLock()
defer sl.lock.RUnlock() defer sl.lock.RUnlock()
svr, _ := sl.addressToServer[addr] return sl.addressToServer[addr]
return svr
} }
func (sl *ServerLookup) Servers() []*metadata.Server { func (sl *ServerLookup) Servers() []*metadata.Server {

View File

@ -820,7 +820,6 @@ func TestServer_BadExpect(t *testing.T) {
type fakeGlobalResp struct{} type fakeGlobalResp struct{}
func (r *fakeGlobalResp) Add(interface{}) { func (r *fakeGlobalResp) Add(interface{}) {
return
} }
func (r *fakeGlobalResp) New() interface{} { 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 // When comparing the tokens disregard the policy link names. This
// data is not cleanly updated in a variety of scenarios and should not // data is not cleanly updated in a variety of scenarios and should not
// be relied upon. // be relied upon.
for i, _ := range tokenCopy.Policies { for i := range tokenCopy.Policies {
tokenCopy.Policies[i].Name = "" tokenCopy.Policies[i].Name = ""
} }
// Also do the same for Role links. // Also do the same for Role links.
for i, _ := range tokenCopy.Roles { for i := range tokenCopy.Roles {
tokenCopy.Roles[i].Name = "" tokenCopy.Roles[i].Name = ""
} }
// The raft indexes won't match either because the requester will not // 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) mux.HandleFunc("/", s.Index)
for pattern, fn := range endpoints { for pattern, fn := range endpoints {
thisFn := fn thisFn := fn
methods, _ := allowedMethods[pattern] methods := allowedMethods[pattern]
bound := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) { bound := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
return thisFn(s, resp, req) return thisFn(s, resp, req)
} }

View File

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

View File

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

View File

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

View File

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

View File

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