////////////////////////////////////////////////////////////////////////// // DN42 GRC API Server ////////////////////////////////////////////////////////////////////////// package main ////////////////////////////////////////////////////////////////////////// import ( "encoding/json" log "github.com/sirupsen/logrus" "net/http" ) ////////////////////////////////////////////////////////////////////////// // Simple event bus type NotifyFunc func(...interface{}) type SimpleEventBus map[string][]NotifyFunc // add a listener to an event func (bus SimpleEventBus) Listen(event string, nfunc NotifyFunc) { bus[event] = append(bus[event], nfunc) } // fire notifications for an event func (bus SimpleEventBus) Fire(event string, params ...interface{}) { funcs := bus[event] if funcs != nil { for _, nfunc := range funcs { nfunc(params...) } } } ////////////////////////////////////////////////////////////////////////// // Return JSON from an API endpoint func ResponseJSON(w http.ResponseWriter, v interface{}) { // for response time testing //time.Sleep(time.Second) // marshal the JSON string data, err := json.Marshal(v) if err != nil { log.WithFields(log.Fields{ "error": err, }).Error("Failed to marshal JSON") } // write back to http handler w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.Write(data) } ////////////////////////////////////////////////////////////////////////// // Set the log level func setLogLevel(levelStr string) { if level, err := log.ParseLevel(levelStr); err != nil { // failed to set the level // set a sensible default and, of course, log the error log.SetLevel(log.InfoLevel) log.WithFields(log.Fields{ "loglevel": levelStr, "error": err, }).Error("Failed to set requested log level") } else { // set the requested level log.SetLevel(level) } } ////////////////////////////////////////////////////////////////////////// // end of code