golint: Untangle if blocks with return in else

This commit is contained in:
Frank Schroeder 2017-04-20 18:59:42 -07:00 committed by Frank Schröder
parent d7e23857ad
commit 3e00e36f41
35 changed files with 170 additions and 210 deletions

View File

@ -547,11 +547,11 @@ func (r *request) toHTTP() (*http.Request, error) {
// Check if we should encode the body
if r.body == nil && r.obj != nil {
if b, err := encodeBody(r.obj); err != nil {
b, err := encodeBody(r.obj)
if err != nil {
return nil, err
} else {
r.body = b
}
r.body = b
}
// Create the HTTP request

View File

@ -143,9 +143,11 @@ func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
// Check if we need to create a session first
l.lockSession = l.opts.Session
if l.lockSession == "" {
if s, err := l.createSession(); err != nil {
s, err := l.createSession()
if err != nil {
return nil, fmt.Errorf("failed to create session: %v", err)
} else {
}
l.sessionRenew = make(chan struct{})
l.lockSession = s
session := l.c.Session()
@ -159,7 +161,6 @@ func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
}
}()
}
}
// Setup the query options
kv := l.c.KV()

View File

@ -155,9 +155,11 @@ func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) {
// Check if we need to create a session first
s.lockSession = s.opts.Session
if s.lockSession == "" {
if sess, err := s.createSession(); err != nil {
sess, err := s.createSession()
if err != nil {
return nil, fmt.Errorf("failed to create session: %v", err)
} else {
}
s.sessionRenew = make(chan struct{})
s.lockSession = sess
session := s.c.Session()
@ -171,7 +173,6 @@ func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) {
}
}()
}
}
// Create the contender entry
kv := s.c.KV()

View File

@ -161,9 +161,8 @@ func (m *aclManager) lookupACL(agent *Agent, id string) (acl.ACL, error) {
if cached != nil && time.Now().Before(cached.Expires) {
metrics.IncrCounter([]string{"consul", "acl", "cache_hit"}, 1)
return cached.ACL, nil
} else {
metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1)
}
metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1)
// At this point we might have a stale cached ACL, or none at all, so
// try to contact the servers.

View File

@ -40,9 +40,8 @@ type MockServer struct {
func (m *MockServer) GetPolicy(args *structs.ACLPolicyRequest, reply *structs.ACLPolicy) error {
if m.getPolicyFn != nil {
return m.getPolicyFn(args, reply)
} else {
return fmt.Errorf("should not have called GetPolicy")
}
return fmt.Errorf("should not have called GetPolicy")
}
func TestACL_Version8(t *testing.T) {

View File

@ -795,9 +795,8 @@ func (a *Agent) SnapshotRPC(args *structs.SnapshotRequest, in io.Reader, out io.
func (a *Agent) Leave() error {
if a.server != nil {
return a.server.Leave()
} else {
return a.client.Leave()
}
return a.client.Leave()
}
// Shutdown is used to hard stop the agent. Should be
@ -895,27 +894,24 @@ func (a *Agent) ForceLeave(node string) (err error) {
func (a *Agent) LocalMember() serf.Member {
if a.server != nil {
return a.server.LocalMember()
} else {
return a.client.LocalMember()
}
return a.client.LocalMember()
}
// LANMembers is used to retrieve the LAN members
func (a *Agent) LANMembers() []serf.Member {
if a.server != nil {
return a.server.LANMembers()
} else {
return a.client.LANMembers()
}
return a.client.LANMembers()
}
// WANMembers is used to retrieve the WAN members
func (a *Agent) WANMembers() []serf.Member {
if a.server != nil {
return a.server.WANMembers()
} else {
return nil
}
return nil
}
// StartSync is called once Services and Checks are registered.
@ -940,9 +936,8 @@ func (a *Agent) ResumeSync() {
func (a *Agent) GetCoordinate() (*coordinate.Coordinate, error) {
if a.config.Server {
return a.server.GetLANCoordinate()
} else {
return a.client.GetCoordinate()
}
return a.client.GetCoordinate()
}
// sendCoordinate is a long-running loop that periodically sends our coordinate
@ -1839,9 +1834,8 @@ func parseMetaPair(raw string) (string, string) {
pair := strings.SplitN(raw, ":", 2)
if len(pair) == 2 {
return pair[0], pair[1]
} else {
return pair[0], ""
}
return pair[0], ""
}
// unloadMetadata resets the local metadata state

View File

@ -155,12 +155,11 @@ func (s *HTTPServer) AgentJoin(resp http.ResponseWriter, req *http.Request) (int
// Get the address
addr := strings.TrimPrefix(req.URL.Path, "/v1/agent/join/")
if wan {
_, err := s.agent.JoinWAN([]string{addr})
return nil, err
_, err = s.agent.JoinWAN([]string{addr})
} else {
_, err := s.agent.JoinLAN([]string{addr})
return nil, err
_, err = s.agent.JoinLAN([]string{addr})
}
return nil, err
}
func (s *HTTPServer) AgentLeave(resp http.ResponseWriter, req *http.Request) (interface{}, error) {

View File

@ -1948,9 +1948,8 @@ func TestAgent_Monitor(t *testing.T) {
if bytes.Contains(resp.Body.Bytes(), expected) {
return true, nil
} else {
return false, fmt.Errorf("didn't see expected")
}
return false, fmt.Errorf("didn't see expected")
}); err != nil {
t.Fatalf("err: %v", err)
}

View File

@ -701,9 +701,8 @@ func (c *CheckDocker) check() {
}
func shell() string {
if otherShell := os.Getenv("SHELL"); otherShell != "" {
return otherShell
} else {
if sh := os.Getenv("SHELL"); sh != "" {
return sh
}
return "/bin/sh"
}
}

View File

@ -1265,44 +1265,44 @@ func FixupCheckType(raw interface{}) error {
if ttl, ok := rawMap[ttlKey]; ok {
ttlS, ok := ttl.(string)
if ok {
if dur, err := time.ParseDuration(ttlS); err != nil {
dur, err := time.ParseDuration(ttlS)
if err != nil {
return err
} else {
rawMap[ttlKey] = dur
}
rawMap[ttlKey] = dur
}
}
if interval, ok := rawMap[intervalKey]; ok {
intervalS, ok := interval.(string)
if ok {
if dur, err := time.ParseDuration(intervalS); err != nil {
dur, err := time.ParseDuration(intervalS)
if err != nil {
return err
} else {
rawMap[intervalKey] = dur
}
rawMap[intervalKey] = dur
}
}
if timeout, ok := rawMap[timeoutKey]; ok {
timeoutS, ok := timeout.(string)
if ok {
if dur, err := time.ParseDuration(timeoutS); err != nil {
dur, err := time.ParseDuration(timeoutS)
if err != nil {
return err
} else {
rawMap[timeoutKey] = dur
}
rawMap[timeoutKey] = dur
}
}
if deregister, ok := rawMap[deregisterKey]; ok {
timeoutS, ok := deregister.(string)
if ok {
if dur, err := time.ParseDuration(timeoutS); err != nil {
dur, err := time.ParseDuration(timeoutS)
if err != nil {
return err
} else {
rawMap[deregisterKey] = dur
}
rawMap[deregisterKey] = dur
}
}

View File

@ -41,9 +41,8 @@ func (s *HTTPServer) KVSEndpoint(resp http.ResponseWriter, req *http.Request) (i
case "GET":
if keyList {
return s.KVSGetKeys(resp, req, &args)
} else {
return s.KVSGet(resp, req, &args)
}
return s.KVSGet(resp, req, &args)
case "PUT":
return s.KVSPut(resp, req, &args)
case "DELETE":
@ -206,9 +205,8 @@ func (s *HTTPServer) KVSPut(resp http.ResponseWriter, req *http.Request, args *s
// Only use the out value if this was a CAS
if applyReq.Op == api.KVSet {
return true, nil
} else {
return out, nil
}
return out, nil
}
// KVSPut handles a DELETE request
@ -252,9 +250,8 @@ func (s *HTTPServer) KVSDelete(resp http.ResponseWriter, req *http.Request, args
// Only use the out value if this was a CAS
if applyReq.Op == api.KVDeleteCAS {
return out, nil
} else {
return true, nil
}
return true, nil
}
// missingKey checks if the key is missing

View File

@ -215,6 +215,7 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re
}
return out, nil
case "PUT":
var args structs.AutopilotSetConfigRequest
s.parseDC(req, &args.Datacenter)
@ -257,9 +258,9 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re
// Only use the out value if this was a CAS
if !args.CAS {
return true, nil
} else {
return reply, nil
}
return reply, nil
default:
resp.WriteHeader(http.StatusMethodNotAllowed)
return nil, nil

View File

@ -83,11 +83,11 @@ func (s *HTTPServer) PreparedQueryGeneral(resp http.ResponseWriter, req *http.Re
func parseLimit(req *http.Request, limit *int) error {
*limit = 0
if arg := req.URL.Query().Get("limit"); arg != "" {
if i, err := strconv.Atoi(arg); err != nil {
i, err := strconv.Atoi(arg)
if err != nil {
return err
} else {
*limit = i
}
*limit = i
}
return nil
}

View File

@ -124,15 +124,13 @@ func (s *HTTPServer) convertOps(resp http.ResponseWriter, req *http.Request) (st
var netKVSize int
for _, in := range ops {
if in.KV != nil {
if size := len(in.KV.Value); size > maxKVSize {
size := len(in.KV.Value)
if size > maxKVSize {
resp.WriteHeader(http.StatusRequestEntityTooLarge)
fmt.Fprintf(resp, "Value for key %q is too large (%d > %d bytes)",
in.KV.Key, size, maxKVSize)
fmt.Fprintf(resp, "Value for key %q is too large (%d > %d bytes)", in.KV.Key, size, maxKVSize)
return nil, 0, false
} else {
netKVSize += size
}
netKVSize += size
verb := api.KVOp(in.KV.Verb)
if isWrite(verb) {

View File

@ -184,12 +184,12 @@ func (c *KVGetCommand) Run(args []string) int {
c.UI.Info(b.String())
return 0
} else {
}
c.UI.Info(string(pair.Value))
return 0
}
}
}
func (c *KVGetCommand) Synopsis() string {
return "Retrieves or lists data from the KV store"

View File

@ -136,13 +136,12 @@ func (c *KVImportCommand) dataFromArgs(args []string) (string, error) {
case '-':
if len(data) > 1 {
return data, nil
} else {
}
var b bytes.Buffer
if _, err := io.Copy(&b, stdin); err != nil {
return "", fmt.Errorf("Failed to read stdin: %s", err)
}
return b.String(), nil
}
default:
return data, nil
}

View File

@ -225,13 +225,12 @@ func (c *KVPutCommand) dataFromArgs(args []string) (string, string, error) {
case '-':
if len(data) > 1 {
return key, data, nil
} else {
}
var b bytes.Buffer
if _, err := io.Copy(&b, stdin); err != nil {
return "", "", fmt.Errorf("Failed to read stdin: %s", err)
}
return key, b.String(), nil
}
default:
return key, data, nil
}

View File

@ -110,8 +110,7 @@ func (c *OperatorAutopilotSetCommand) Run(args []string) int {
if result {
c.UI.Output("Configuration updated!")
return 0
} else {
}
c.UI.Output("Configuration could not be atomically updated, please try again")
return 1
}
}

View File

@ -170,9 +170,8 @@ func (c *aclCache) lookupACL(id, authDC string) (acl.ACL, error) {
if cached != nil && time.Now().Before(cached.Expires) {
metrics.IncrCounter([]string{"consul", "acl", "cache_hit"}, 1)
return cached.ACL, nil
} else {
metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1)
}
metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1)
// Attempt to refresh the policy from the ACL datacenter via an RPC.
args := structs.ACLPolicyRequest{
@ -192,9 +191,8 @@ func (c *aclCache) lookupACL(id, authDC string) (acl.ACL, error) {
// other error we report it in the logs but can continue.
if strings.Contains(err.Error(), aclNotFound) {
return nil, errors.New(aclNotFound)
} else {
c.logger.Printf("[ERR] consul.acl: Failed to get policy from ACL datacenter: %v", err)
}
c.logger.Printf("[ERR] consul.acl: Failed to get policy from ACL datacenter: %v", err)
// TODO (slackpad) - We could do a similar thing *within* the ACL
// datacenter if the leader isn't available. We have a local state
@ -729,19 +727,18 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest,
// Service-level check for some other service. Make sure they've
// got write permissions for that service.
if ns == nil {
return fmt.Errorf("Unknown service '%s' for check '%s'",
check.ServiceID, check.CheckID)
} else {
return fmt.Errorf("Unknown service '%s' for check '%s'", check.ServiceID, check.CheckID)
}
other, ok := ns.Services[check.ServiceID]
if !ok {
return fmt.Errorf("Unknown service '%s' for check '%s'",
check.ServiceID, check.CheckID)
return fmt.Errorf("Unknown service '%s' for check '%s'", check.ServiceID, check.CheckID)
}
if !acl.ServiceWrite(other.Service) {
return errPermissionDenied
}
}
}
return nil
}

View File

@ -46,9 +46,8 @@ func (a *aclIterator) Less(i, j int) bool {
func (a *aclIterator) Front() *structs.ACL {
if a.index < len(a.acls) {
return a.acls[a.index]
} else {
return nil
}
return nil
}
// Next advances the iterator to the next index.

View File

@ -63,9 +63,8 @@ func (t *txnResultsFilter) Filter(i int) bool {
result := t.results[i]
if result.KV != nil {
return !t.acl.KeyRead(result.KV.Key)
} else {
return false
}
return false
}
func (t *txnResultsFilter) Move(dst, src, span int) {

View File

@ -111,9 +111,8 @@ func (c *consulFSM) Apply(log *raft.Log) interface{} {
if ignoreUnknown {
c.logger.Printf("[WARN] consul.fsm: ignoring unknown message type (%d), upgrade to newer version", msgType)
return nil
} else {
panic(fmt.Errorf("failed to apply request: %#v", buf))
}
panic(fmt.Errorf("failed to apply request: %#v", buf))
}
}
@ -176,32 +175,28 @@ func (c *consulFSM) applyKVSOperation(buf []byte, index uint64) interface{} {
act, err := c.state.KVSDeleteCAS(index, req.DirEnt.ModifyIndex, req.DirEnt.Key)
if err != nil {
return err
} else {
return act
}
return act
case api.KVDeleteTree:
return c.state.KVSDeleteTree(index, req.DirEnt.Key)
case api.KVCAS:
act, err := c.state.KVSSetCAS(index, &req.DirEnt)
if err != nil {
return err
} else {
return act
}
return act
case api.KVLock:
act, err := c.state.KVSLock(index, &req.DirEnt)
if err != nil {
return err
} else {
return act
}
return act
case api.KVUnlock:
act, err := c.state.KVSUnlock(index, &req.DirEnt)
if err != nil {
return err
} else {
return act
}
return act
default:
err := fmt.Errorf("Invalid KVS operation '%s'", req.Op)
c.logger.Printf("[WARN] consul.fsm: %v", err)
@ -219,9 +214,8 @@ func (c *consulFSM) applySessionOperation(buf []byte, index uint64) interface{}
case structs.SessionCreate:
if err := c.state.SessionCreate(index, &req.Session); err != nil {
return err
} else {
return req.Session.ID
}
return req.Session.ID
case structs.SessionDestroy:
return c.state.SessionDestroy(index, req.Session.ID)
default:
@ -240,9 +234,8 @@ func (c *consulFSM) applyACLOperation(buf []byte, index uint64) interface{} {
case structs.ACLForceSet, structs.ACLSet:
if err := c.state.ACLSet(index, &req.ACL); err != nil {
return err
} else {
return req.ACL.ID
}
return req.ACL.ID
case structs.ACLDelete:
return c.state.ACLDelete(index, req.ACL.ID)
default:
@ -326,13 +319,11 @@ func (c *consulFSM) applyAutopilotUpdate(buf []byte, index uint64) interface{} {
act, err := c.state.AutopilotCASConfig(index, req.Config.ModifyIndex, &req.Config)
if err != nil {
return err
} else {
}
return act
}
} else {
return c.state.AutopilotSetConfig(index, &req.Config)
}
}
func (c *consulFSM) Snapshot() (raft.FSMSnapshot, error) {
defer func(start time.Time) {

View File

@ -627,7 +627,7 @@ func (s *Server) joinConsulServer(m serf.Member, parts *agent.Server) error {
// Exit with no-op if this is being called on an existing server
if server.Address == raft.ServerAddress(addr) && server.ID == raft.ServerID(parts.ID) {
return nil
} else {
}
future := s.raft.RemoveServer(server.ID, 0, 0)
if server.Address == raft.ServerAddress(addr) {
if err := future.Error(); err != nil {
@ -642,7 +642,6 @@ func (s *Server) joinConsulServer(m serf.Member, parts *agent.Server) error {
}
}
}
}
// Attempt to add as a peer
switch {

View File

@ -383,9 +383,8 @@ func TestLeader_Reconcile_Races(t *testing.T) {
if node != nil {
nodeAddr = node.Address
return true, nil
} else {
return false, nil
}
return false, nil
}); err != nil {
t.Fatalf("client should be registered: %v", err)
}

View File

@ -311,7 +311,8 @@ func (p *ConnPool) getNewConn(dc string, addr net.Addr, version int) (*Conn, err
if version < 2 {
conn.Close()
return nil, fmt.Errorf("cannot make client connection, unsupported protocol version %d", version)
} else {
}
// Write the Consul multiplex byte to set the mode
if _, err := conn.Write([]byte{byte(rpcMultiplexV2)}); err != nil {
conn.Close()
@ -324,7 +325,6 @@ func (p *ConnPool) getNewConn(dc string, addr net.Addr, version int) (*Conn, err
// Create a multiplexed session
session, _ = yamux.Client(conn, conf)
}
// Wrap the connection
c := &Conn{

View File

@ -130,9 +130,8 @@ func (ct *CompiledTemplate) Render(name string) (*structs.PreparedQuery, error)
i, ok := inputs[0].(int)
if ok && i >= 0 && i < len(matches) {
return matches[i], nil
} else {
return "", nil
}
return "", nil
},
}

View File

@ -2758,9 +2758,8 @@ func (m *mockQueryServer) ForwardDC(method, dc string, args interface{}, reply i
}
if m.QueryFn != nil {
return m.QueryFn(dc, args, reply)
} else {
return nil
}
return nil
}
func TestPreparedQuery_queryFailover(t *testing.T) {

View File

@ -334,9 +334,8 @@ func NewServer(config *Config) (*Server, error) {
portFn := func(s *agent.Server) (int, bool) {
if s.WanJoinPort > 0 {
return s.WanJoinPort, true
} else {
return 0, false
}
return 0, false
}
go s.Flood(portFn, s.serfWAN)

View File

@ -207,14 +207,14 @@ func (m *Manager) FindServer() *agent.Server {
if numServers == 0 {
m.logger.Printf("[WARN] manager: No servers available")
return nil
} else {
}
// Return whatever is at the front of the list because it is
// assumed to be the oldest in the server list (unless -
// hypothetically - the server list was rotated right after a
// server was added).
return l.servers[0]
}
}
// getServerList is a convenience method which hides the locking semantics
// of atomic.Value from the caller.

View File

@ -712,9 +712,8 @@ func (s *Store) NodeService(nodeName string, serviceID string) (uint64, *structs
if service != nil {
return idx, service.(*structs.ServiceNode).ToNodeService(), nil
} else {
return idx, nil, nil
}
return idx, nil, nil
}
// NodeServices is used to query service registrations by node name or UUID.
@ -962,9 +961,8 @@ func (s *Store) NodeCheck(nodeName string, checkID types.CheckID) (uint64, *stru
if check != nil {
return idx, check.(*structs.HealthCheck), nil
} else {
return idx, nil, nil
}
return idx, nil, nil
}
// NodeChecks is used to retrieve checks associated with the

View File

@ -298,9 +298,8 @@ func (s *Store) PreparedQueryResolve(queryIDOrName string) (uint64, *structs.Pre
return idx, nil, err
}
return idx, render, nil
} else {
return idx, wrapper.PreparedQuery, nil
}
return idx, wrapper.PreparedQuery, nil
}
// Next, look for an exact name match. This is the common case for static

View File

@ -60,21 +60,21 @@ func Setup(config *Config, ui cli.Ui) (*logutils.LevelFilter, *GatedWriter, *Log
delay := 5 * time.Second
for i := 0; i <= retries; i++ {
l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, "consul")
if err != nil {
if err == nil {
syslog = &SyslogWrapper{l, logFilter}
break
}
ui.Error(fmt.Sprintf("Syslog setup error: %v", err))
if i == retries {
timeout := time.Duration(retries) * delay
ui.Error(fmt.Sprintf("Syslog setup did not succeed within timeout (%s).", timeout.String()))
return nil, nil, nil, nil, false
} else {
}
ui.Error(fmt.Sprintf("Retrying syslog setup in %s...", delay.String()))
time.Sleep(delay)
}
} else {
syslog = &SyslogWrapper{l, logFilter}
break
}
}
}
// Create a log writer, and wrap a logOutput around it

View File

@ -35,9 +35,8 @@ func WaitForResult(try testFn) error {
}
if err != nil {
return errors.Wrap(err, "timed out with error")
} else {
return fmt.Errorf("timed out")
}
return fmt.Errorf("timed out")
}
type rpcFn func(string, interface{}, interface{}) error

View File

@ -33,7 +33,6 @@ func WaitForResult(try testFn) error {
}
if err != nil {
return errors.Wrap(err, "timed out with error")
} else {
}
return fmt.Errorf("timed out")
}
}

View File

@ -213,21 +213,21 @@ func (c *Config) OutgoingTLSWrapper() (DCWrapper, error) {
// Strip the trailing '.' from the domain if any
domain := strings.TrimSuffix(c.Domain, ".")
wrapper := func(dc string, c net.Conn) (net.Conn, error) {
return WrapTLSClient(c, tlsConfig)
}
// Generate the wrapper based on hostname verification
if c.VerifyServerHostname {
wrapper := func(dc string, conn net.Conn) (net.Conn, error) {
wrapper = func(dc string, conn net.Conn) (net.Conn, error) {
conf := clone(tlsConfig)
conf.ServerName = "server." + dc + "." + domain
return WrapTLSClient(conn, conf)
}
return wrapper, nil
} else {
wrapper := func(dc string, c net.Conn) (net.Conn, error) {
return WrapTLSClient(c, tlsConfig)
}
return wrapper, nil
}
}
// SpecificDC is used to invoke a static datacenter
// and turns a DCWrapper into a Wrapper type.