github.com/deemoprobe/k8s-first-commit@v0.0.0-20230430165612-a541f1982be3/pkg/util/util.go (about)

     1  /*
     2  Copyright 2014 Google Inc. All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  package util
    17  
    18  import (
    19  	"encoding/json"
    20  	"log"
    21  	"time"
    22  )
    23  
    24  // Simply catches a crash and logs an error. Meant to be called via defer.
    25  func HandleCrash() {
    26  	r := recover()
    27  	if r != nil {
    28  		log.Printf("Recovered from panic: %#v", r)
    29  	}
    30  }
    31  
    32  // Loops forever running f every d.  Catches any panics, and keeps going.
    33  func Forever(f func(), period time.Duration) {
    34  	for {
    35  		func() {
    36  			defer HandleCrash()
    37  			f()
    38  		}()
    39  		time.Sleep(period)
    40  	}
    41  }
    42  
    43  // Returns o marshalled as a JSON string, ignoring any errors.
    44  func MakeJSONString(o interface{}) string {
    45  	data, _ := json.Marshal(o)
    46  	return string(data)
    47  }