func writeLevelDB(channel string, userName string, userMessage string, levelId string) { chanId := channels[channel] //Check for duplicate LevelId for this channel var duplicateLevel string checkDuplicate := db.QueryRow("SELECT Level FROM Levels WHERE Level=? AND StreamID=?;", levelId, chanId).Scan(&duplicateLevel) switch { case checkDuplicate == sql.ErrNoRows: color.Green("No such level, Adding...\n") insertLevel, dberr := db.Prepare("INSERT Levels SET StreamID=?,Nick=?,Level=?,Message=?,Added=?;") if dberr != nil { log.Fatalf("Cannot prepare insertLevel on %s: %s\n", channel, dberr.Error()) } defer insertLevel.Close() timeNow := time.Now().Format(time.RFC3339) execLevel, dberr := insertLevel.Exec(chanId, userName, levelId, userMessage, timeNow) if dberr != nil { log.Fatalf("Cannot exec insertLevel on %s: %s\n", channel, dberr.Error()) } rowsAff, dberr := execLevel.RowsAffected() if dberr != nil { log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error()) } lastId, dberr := execLevel.LastInsertId() if dberr != nil { log.Fatalf("No last id on %s: %s\n", channel, dberr.Error()) } color.Green("Added level %s by %s for %d %s. Row|#: %d|%d\n", levelId, userName, chanId, channel, rowsAff, lastId) case checkDuplicate != nil: log.Fatalf("Checking duplicate level failed, error: %s\n", checkDuplicate.Error()) default: color.Yellow("Duplicate level, not adding...\n") } }
func testRCCSend() { if err := rpio.Open(); err != nil { fmt.Println(err) os.Exit(1) } defer rpio.Close() rccPin.Output() testCode := [13]int{1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0} // Toggle pin 20 times for x := 0; x < len(testCode); x++ { state := testCode[x] if state == 1 { color.Green("High: ", state) rccPin.High() } else { color.Green("Low: ", state) rccPin.Low() } time.Sleep(300) } }
func startNotice() { color.Green("******") color.Green("~ Notice: ~\n") color.White("When your download is complete,\nyou will find your files under:\n") color.Magenta(setDownloadFolder()) color.Green("******" + "\n\n") }
func main() { Repo := [6]string{"https://github.com/EgeBalci/ARCANUS/blob/master/SOURCE/ARCANUS.go", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x64", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x64.exe", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x86", "https://github.com/EgeBalci/ARCANUS/raw/master/ARCANUS_x86.exe", "https://github.com/EgeBalci/ARCANUS/raw/master/README.md"} if runtime.GOOS == "windows" { exec.Command("cmd", "/C", "msg ARCANUS Update Started...").Run() exec.Command("cmd", "/C", "del ARCANUS.go").Run() exec.Command("cmd", "/C", "del ARCANUS_x64.exe").Run() exec.Command("cmd", "/C", "del ARCANUS_x86.exe").Run() exec.Command("cmd", "/C", "del ARCANUS_x64").Run() exec.Command("cmd", "/C", "del ARCANUS_x86").Run() color.Blue("[*] Updating ARCANUS...\n\n") for i := 0; i < len(Repo); i++ { response, _ := http.Get(Repo[i]) defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) Name := strings.Split(Repo[i], "/") color.Green("# " + string(Name[(len(Name)-1)]) + " [OK]") file, _ := os.Create(string(Name[(len(Name) - 1)])) file.WriteString(string(body)) } /*ARC, _ := exec.Command("cmd", "/C", "echo %PROCESSOR_ARCHITECTURE%").Output() if strings.Contains(string(ARC), "x86") || strings.Contains(string(ARC), "X86") { exec.Command("cmd", "/C", "ARCANUS_x86.exe").Start() }else if strings.Contains(string(ARC), "AMD64") { exec.Command("cmd", "/C", "ARCANUS_x64.exe").Start() }*/ exec.Command("cmd", "/C", "msg * ARCANUS Updated Succesfuly !").Run() } else if runtime.GOOS == "linux" { exec.Command("sh", "-c", "zenity --info --text=\"ARCANUS Update Started... \"").Run() exec.Command("sh", "-c", "rm ARCANUS.go").Run() exec.Command("sh", "-c", "rm ARCANUS_x64.exe").Run() exec.Command("sh", "-c", "rm ARCANUS_x86.exe").Run() exec.Command("sh", "-c", "rm ARCANUS_x64").Run() exec.Command("sh", "-c", "rm ARCANUS_x86").Run() color.Blue("[*] Updating ARCANUS...\n\n") for i := 0; i < len(Repo); i++ { response, _ := http.Get(Repo[i]) defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) Name := strings.Split(Repo[i], "/") color.Green("# " + string(Name[(len(Name)-1)]) + " [OK]") file, _ := os.Create(string(Name[(len(Name) - 1)])) file.WriteString(string(body)) } exec.Command("sh", "-c", "zenity --info --text=\"ARCANUS Updated Succesfuly !\"").Run() /*ARC, _ := exec.Command("sh", "-c", "uname -a").Output() if strings.Contains(string(ARC), "x86") || strings.Contains(string(ARC), "X86") { exec.Command("sh", "-c", "./ARCANUS_x86").Start() }else if strings.Contains(string(ARC), "amd64") { exec.Command("sh", "-c", "./ARCANUS_x64").Start() }*/ } }
func endNotice() { fmt.Print("\n\n") color.Green("******") color.Green("Download complete!\n") color.White("Your files have been saved to " + setDownloadFolder() + "\n\n") color.White("For your convenience, your files have been sorted by extension.") color.Green("******") }
func handleInteractiveMode() { reader := bufio.NewReader(os.Stdin) for { red := color.New(color.FgCyan) red.Printf("%s %s %s => ", time.Now().Format("15:04:05"), *serverFlag, *executorFlag) line, err := reader.ReadString('\n') if err != nil { log.Fatal(color.RedString("ERROR reading string: %s", err.Error())) } line = strings.Trim(line, "\r\n") if strings.EqualFold(line, "exit") { color.Green("Exit command received. Good bye.") os.Exit(0) } exeAndArgs, err := parsecommand.Parse(line) if err != nil { color.Red("Cannot parse line '%s', error: %s", line, err.Error()) continue } var exe string var args []string = []string{} exe = exeAndArgs[0] if len(exeAndArgs) > 1 { args = exeAndArgs[1:] } onFeedback := func(fb string) { fmt.Println(fb) } color.Green("Exe '%s' and args '%#v'", exe, args) color.Yellow("-------------------------------------") println() err = execute(false, onFeedback, *serverFlag, *executorFlag, *clientPemFlag, exe, args...) if err != nil { color.Red("Execute failed with error: %s", err.Error()) continue } println() color.Yellow("-------------------------------------") println() println() } }
func runAllProcessorTests(t *testing.T, cases map[string]processorTestCase) { color.NoColor = false json := `{ "var1": "var1", "var-var": "var-var", "var": {"var": "1"}, "version": "{{ feature }}-{{ feature-suffix }}", "feature": "value-unknown", "feature-suffix": "{{ feature }}", "list": [1, 2, 3] }` tree, err := gabs.ParseJSON([]byte(json)) if err != nil { color.Red("%v: failed!\n", err) t.Fail() } for name, test := range cases { if res, err := Template(test.in, tree); err == nil { if test.expect == res { color.Green("%v: Ok\n", name) } else { color.Red("%v: %v != %v: failed!\n", name, test.expect, res) t.Fail() } } else { color.Red("error %v\n: failed!", err) t.Fail() } } }
func exec(cmd *cobra.Command, args []string) { if len(args) == 1 { color.Green("Creando nueva aplicacion " + args[0]) gopath := os.Getenv("GOPATHs") if gopath == "" { color.Set(color.FgRed) defer color.Unset() log.Fatalln("GOPATH no found :(") os.Exit(2) } src := fmt.Sprintf("%s\\src", gopath) appName := args[0] appDir := fmt.Sprintf("%s\\%s", src, appName) createAppFolder(appDir, []string{}) fmt.Printf("appDir: %s\n", appDir) createAppFolder(fmt.Sprintf("%s\\%s", appDir, "public"), []string{"assets"}) createAppFolder(fmt.Sprintf("%s\\%s", appDir, "app"), []string{"controllers", "models"}) createSubFolder(fmt.Sprintf("%s\\%s\\%s", appDir, "public", "assets"), []string{"js", "scss", "img", "fonts"}) // creamos la estructura basica } }
func TestPlugin(t *testing.T) { color.NoColor = false casses := map[string]testrunnerTestCase{ "simple": { first: map[string]interface{}{"name": "value"}, second: map[string]interface{}{"name": "value"}, expect: make(map[string]interface{}), }, "diff": { first: map[string]interface{}{"name1": "value"}, second: map[string]interface{}{"name": "value"}, expect: map[string]interface{}{"name": "<nil> != value", "name1": "value != <nil>"}, }, } for name, test := range casses { if d := diff(test.first, test.second); !reflect.DeepEqual(d, test.expect) { color.Red("\n\nTest `%s` failed!", name) color.Yellow("\n\nexpected: %v\n\ngiven: %v\n\n", test.expect, d) t.Fail() } else { color.Green("\n%s: OK\n", name) } } }
// Run initializes runner with given parameters. func (r *Runner) Run(p *Params) { for fileName := range r.start { color.Green("Running %s...\n", p.Get("run")) cmd, err := runCommand(fileName, p.Package...) if err != nil { log.Printf("Could not run the go binary: %s \n", err) r.kill() continue } r.mu.Lock() r.cmd = cmd removeFile(fileName) r.mu.Unlock() go func(cmd *exec.Cmd) { if err := cmd.Wait(); err != nil { log.Printf("process interrupted: %s \n", err) r.kill() } }(r.cmd) } }
// Init basic strctures in the database func initDatabase(dbPath string) (*bolt.DB, error) { db, err := bolt.Open(dbPath, 0600, nil) if err != nil { return nil, err } color.Green("[DB: OK]") // Init buckets if not present for i := 0; i < 2; i++ { err = db.Update(func(tx *bolt.Tx) error { switch i { // Init a bucket for the devices case 0: _, err := tx.CreateBucketIfNotExists([]byte("devices")) if err != nil { return fmt.Errorf("create bucket: %s", err) } return nil // Init a bucket for the rooms default: _, err := tx.CreateBucketIfNotExists([]byte("rooms")) if err != nil { return fmt.Errorf("create bucket: %s", err) } return nil } }) } if err != nil { log.Fatal("Could not create bucket in DB", err) } return db, nil }
func TestAnchorMerger(t *testing.T) { color.NoColor = false in := []byte(`--- vars: &v env: qa deploy: env: live`) expect := `{"deploy":{"env":"live"},"vars":{"env":"qa"}}` if err := ioutil.WriteFile("/tmp/test", in, 0644); err != nil { color.Red("Error file not create") t.Error("Error file not create") t.Fail() } defer os.Remove("/tmp/test") if g, err := LoadFile("/tmp/test"); err != nil { color.Red("%v\n", err) t.Error(err) t.Fail() } else { if g.String() == expect { color.Green("\n%s: OK\n", "FileLoad") } else { color.Red("%s != %s", g.String(), expect) t.Error(fmt.Errorf("%s != %s", g.String(), expect)) t.Fail() } } }
// Debugf is a convenience method appending a debug message to the logger func Debugf(msg string, a ...interface{}) { _, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf(msg, a...) msg = fmt.Sprintf("%+v%s:%d\n\n", msg, fn, line) formattedMessage := formattedLogMessage("DEBUG", msg) color.Green(formattedMessage) }
func (r Documentation) Output(results <-chan []resource.TestResult) (hasFail bool) { testCount := 0 var failed []resource.TestResult for resultGroup := range results { for _, testResult := range resultGroup { if testResult.Successful { fmt.Println(humanizeResult(testResult)) testCount++ } else { fmt.Println(humanizeResult(testResult)) failed = append(failed, testResult) testCount++ } } fmt.Println("") } fmt.Print("\n") if len(failed) > 0 { color.Red("Failures:") for _, testResult := range failed { fmt.Println(humanizeResult(testResult)) } fmt.Print("\n") } if len(failed) > 0 { color.Red("Count: %d failed: %d\n", testCount, len(failed)) return true } color.Green("Count: %d failed: %d\n", testCount, len(failed)) return false }
//Hit the chosen URL using a GET request and signal its completion using the waitGroup //Prints out the URL and the Status code to the command line func hitUrl(url string, failedUrl chan string) { req, err := http.NewRequest("GET", url, nil) //Add me some akamai debug headers req.Header.Add("Pragma", "akamai-x-cache-on, akamai-x-check-cacheable") client := &http.Client{} resp, err := client.Do(req) if err != nil { failedUrl <- err.Error() return } //trim out everthing that isn't the cache hit type fromIndex := strings.Index(resp.Header.Get("X-Cache"), " from") cacheHit := "No Cache header" if fromIndex > 0 { cacheHit = resp.Header.Get("X-Cache")[:fromIndex] } responseString := fmt.Sprintf("Is cacheable? %s \t Cache hit: %s \t Url : %s Status: %s \n", resp.Header.Get("X-Check-Cacheable"), cacheHit, url, resp.Status) if resp.StatusCode == http.StatusOK { color.Green(responseString) } else { failedUrl <- responseString } }
// Debug is a convenience method appending a debug message to the logger func Debug(obj interface{}) { // Get the line number and calling func sig _, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%+v\n%s:%d\n\n", obj, fn, line) formattedMessage := formattedLogMessage("DEBUG", msg) color.Green(formattedMessage) }
func logIRC(irc map[string]string) { if _, err := os.Stat("./logs"); err != nil { if os.IsNotExist(err) { color.Green("Creating directory logs") os.Mkdir("./logs", 0766) } } if strings.HasPrefix(irc["params"], "#") { s := strings.Split(irc["params"], " ") f, err := os.OpenFile("logs/"+s[0]+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening logfile for %s: %v", irc["params"], err) } log.SetOutput(f) log.Printf("%s %s %s %s\n", irc["prefix"], irc["command"], irc["params"], irc["trailing"]) defer f.Close() } else { f, err := os.OpenFile("logs/all.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening logfile all: %v", err) } log.SetOutput(f) log.Printf("%s %s %s %s %s\n", irc["tags"], irc["prefix"], irc["command"], irc["params"], irc["trailing"]) defer f.Close() } }
func (r Rspecish) Output(results <-chan []resource.TestResult, startTime time.Time) (exitCode int) { testCount := 0 var failed []resource.TestResult for resultGroup := range results { for _, testResult := range resultGroup { if testResult.Successful { fmt.Printf(green(".")) } else { fmt.Printf(red("F")) failed = append(failed, testResult) } testCount++ } } fmt.Print("\n\n") if len(failed) > 0 { color.Red("Failures:") for _, testResult := range failed { fmt.Println(humanizeResult(testResult)) } fmt.Print("\n") } fmt.Printf("Total Duration: %.3fs\n", time.Since(startTime).Seconds()) if len(failed) > 0 { color.Red("Count: %d, Failed: %d\n", testCount, len(failed)) return 1 } color.Green("Count: %d, Failed: %d\n", testCount, len(failed)) return 0 }
// Read in and parse the congig // path: Path to config file func initConf(path string) error { // Load settings from conf.json file, err := os.Open(path) decoder := json.NewDecoder(file) // Could not load config file. if err != nil { color.Red("ERROR:", err) if path != "conf.json" { fmt.Println("Looking in current directory") initConf("./conf.json") } return err } // Handle parsing errors err = decoder.Decode(&Conf) if err != nil { fmt.Println("error:", err.Error()) return err } if Debug { color.Green("[SETTINGS: OK]") fmt.Println("Settings Data:", Conf) } return nil }
func lockPackages(b *BunchFile) error { err := setVendorEnv() if err != nil { return errors.Trace(err) } lockList := make(map[string]string) for _, pack := range b.Packages { if pack.IsLink { continue } _, recency, err := checkPackageRecency(pack) if err != nil { return errors.Trace(err) } lockList[pack.Repo] = recency.LatestCommit } jsonOut, err := json.MarshalIndent(lockList, "", " ") if err != nil { return errors.Trace(err) } else { err = ioutil.WriteFile("Bunchfile.lock", append(jsonOut, '\n'), 0644) if err != nil { return errors.Trace(err) } color.Green("Bunchfile.lock generated successfully") } return nil }
func writeLevelDB(channel string, userName string, userMessage string, levelID string) { chanID := channels[channel] //Check for duplicate LevelId for this channel var duplicateLevel string var info map[string]string var exist bool info = make(map[string]string) err := try.Do(func(attempt int) (bool, error) { var err error info, exist, err = fetchInfo(levelID) return attempt < 5, err // try 5 times }) if err != nil { log.Println("Error: " + err.Error()) } else if exist { checkDuplicate := db.QueryRow("SELECT Level FROM Levels WHERE Level=? AND StreamID=?;", levelID, chanID).Scan(&duplicateLevel) switch { case checkDuplicate == sql.ErrNoRows: color.Green("No such level, Adding...\n") insertLevel, dberr := db.Prepare("INSERT Levels SET StreamID=?,Nick=?,Level=?,Message=?,Added=?,Removed=?,Title=?,Difficulty=?,Style=?,Creator=?,Flag=?,Created=?,Tags=?,Image=?,ImageFull=?;") if dberr != nil { log.Fatalf("Cannot prepare insertLevel on %s: %s\n", channel, dberr.Error()) } defer insertLevel.Close() timeNow := time.Now().Format(time.RFC3339) execLevel, dberr := insertLevel.Exec(chanID, userName, levelID, userMessage, timeNow, 0, info["title"], info["diff"], info["style"], info["name"], info["flag"], info["created"], info["tags"], info["img"], info["imgfull"]) if dberr != nil { log.Fatalf("Cannot exec insertLevel on %s: %s\n", channel, dberr.Error()) } rowsAff, dberr := execLevel.RowsAffected() if dberr != nil { log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error()) } lastID, dberr := execLevel.LastInsertId() if dberr != nil { log.Fatalf("No lastID on %s: %s\n", channel, dberr.Error()) } color.Green("Added level %s by %s for %d %s. Row|#: %d|%d\n", levelID, userName, chanID, channel, rowsAff, lastID) case checkDuplicate != nil: log.Fatalf("Checking duplicate level failed, error: %s\n", checkDuplicate.Error()) default: color.Yellow("Duplicate level, not adding...\n") } } else { color.Yellow("Level doesn't exist...\n") } }
func main() { argsWithoutProg := os.Args[1:] if len(argsWithoutProg) == 0 { fmt.Println("Usage: go run sum.go filter") return } filter := strings.Join(argsWithoutProg, " ") file, err := os.Open("diff.txt") check(err) defer file.Close() var added, removed uint64 re, err := regexp.Compile(`(.+)\:`) scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if len(line) > 3 && strings.Contains(line[3:], filter) { if line[0:3] == "Inc" || line[0:3] == "New" { res := re.FindStringSubmatch(line[4:]) if len(res) > 0 { added += SizeInBytes(res[1]) } } else if line[0:3] == "Dec" || line[0:3] == "Rem" { res := re.FindStringSubmatch(line[4:]) if len(res) > 0 { removed += SizeInBytes(res[1]) } } } } color.Green("Added: " + bytefmt.ByteSize(added)) color.Yellow("Removed: " + bytefmt.ByteSize(removed)) diff := int64(added) - int64(removed) if diff < 0 { color.Yellow("= Net total: -" + bytefmt.ByteSize(uint64(-diff))) } else { color.Green("= Net total: " + bytefmt.ByteSize(uint64(diff))) } }
func TesTMovingJid(t *testing.T) { jid := jobworker.GetPendingJids("parsebin") jobworker.MoveJidToProcessingSet("parsebin", jid) color.Green("%v", jid) }
func PrintMessage(cl int, msg string) { if cl == 0 { color.Green("[pixmate] %s", msg) } else if cl == 1 { color.Red("[pixmate] %s", msg) } else if cl == 2 { color.Cyan("[pixmate] %s", msg) } }
func react(hostname, execute string, changes <-chan string) { changed := <-changes output, error := exec.Command(execute).Output() if error != nil { color.Red("[ERROR] %s", error) } else { color.Green("[CHANGE] %s %s", changed, output) } }
func writeSubs(channel string, name string, months string) { chanId := channels[channel] var monthsTotal int var subID int checkSub := db.QueryRow("SELECT SubID,MonthsTotal FROM Subscribers WHERE Nick=? AND StreamID=?;", name, chanId).Scan(&subID, &monthsTotal) switch { case checkSub == sql.ErrNoRows: color.Green("No such subscriber, Adding...\n") insertSub, dberr := db.Prepare("INSERT Subscribers SET StreamID=?,Nick=?,MonthsInRow=?,MonthsTotal=?,Lastsub=?;") if dberr != nil { log.Fatalf("Cannot prepare insertSub on %s: %s\n", channel, dberr.Error()) } defer insertSub.Close() timeNow := time.Now().Format(time.RFC3339) execSub, dberr := insertSub.Exec(chanId, name, months, months, timeNow) if dberr != nil { log.Fatalf("Cannot exec insertSub on %s: %s\n", channel, dberr.Error()) } rowsAff, dberr := execSub.RowsAffected() if dberr != nil { log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error()) } color.Green("Added Sub %s for %s months on %s, %d\n", name, months, channel, rowsAff) case checkSub != nil: log.Fatalf("Checking for subs failed, error: %s\n", checkSub.Error()) default: updateSub, dberr := db.Prepare("UPDATE Subscribers SET MonthsInRow=?,MonthsTotal=?,Lastsub=? WHERE SubID=?;") if dberr != nil { log.Fatalf("Cannot prepare updateSub on %s: %s\n", channel, dberr.Error()) } newTotal := monthsTotal + 1 timeNow := time.Now().Format(time.RFC3339) execSubU, dberr := updateSub.Exec(months, newTotal, timeNow, subID) if dberr != nil { log.Fatalf("Cannot exec updateSub on %s: %s\n", channel, dberr.Error()) } rowsAff, dberr := execSubU.RowsAffected() if dberr != nil { log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error()) } color.Green("Updated sub %s for %s months and %d total months on %s, %d\n", name, months, newTotal, channel, rowsAff) } }
//Connect connects to twitch irc func Connect() { var err error color.Yellow("Connecting...\n") conn, err = net.Dial("tcp", server+":"+port) if err != nil { color.Red("Unable to connect to Twitch IRC server! Reconnecting in 10 seconds...\n") time.Sleep(10 * time.Second) Connect() } color.Green("Connected to IRC server %s\n", server) }
func (m *Manager) comment(issue string, text string) { resp, err := http.PostForm(m.URL+"/issues/"+issue+"/comment", url.Values{"body": {text}}) if err != nil { color.Red("Couldn't connect to the server") } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) color.Green(string(body)) }
func DisplayInfo() { color.Yellow("\n\n******* GO WORKER INFORMATION *******\n\n") infoObj := GetInfoObj() color.Green("%+v", infoObj) color.Yellow("\n\n*************************************\n\n") }
func InitDB() { db, dberr = sql.Open("mysql", database) if dberr != nil { log.Fatalf("Error on initializing database connection: %s", dberr.Error()) } //[MySQL] packets.go:118: write unix /var/lib/mysql/mysql.sock: broken pipe db.SetMaxIdleConns(0) //Create tables _, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Streamers ( StreamID MEDIUMINT NOT NULL, Name VARCHAR(25) NOT NULL UNIQUE, PRIMARY KEY (StreamID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;") if dberr != nil { log.Fatalf("Error on initializing table Streamers: %s", dberr.Error()) } _, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Levels ( LevelID MEDIUMINT NOT NULL AUTO_INCREMENT, StreamID MEDIUMINT NOT NULL, Nick VARCHAR(25) NOT NULL, Level VARCHAR(22) NOT NULL, Message VARCHAR(255) NOT NULL, Comment VARCHAR(255) NOT NULL, Played BOOLEAN NOT NULL, Skipped BOOLEAN NOT NULL, Added DATETIME NOT NULL, Passed DATETIME NOT NULL,PRIMARY KEY (LevelID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;") if dberr != nil { log.Fatalf("Error on initializing table Levels: %s", dberr.Error()) } _, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Subscribers ( SubID MEDIUMINT NOT NULL AUTO_INCREMENT, StreamID MEDIUMINT NOT NULL, Nick VARCHAR(25) NOT NULL, MonthsInRow TINYINT NOT NULL, MonthsTotal TINYINT NOT NULL, Lastsub DATETIME NOT NULL,PRIMARY KEY (SubID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;") if dberr != nil { log.Fatalf("Error on initializing table Subscribers: %s", dberr.Error()) } blue := color.New(color.FgBlue).SprintFunc() var Streamer int fmt.Printf("dbStreamers: ") for k, i := range channels { chanName := strings.Replace(k, "#", "", 1) checkStream := db.QueryRow("SELECT StreamID FROM Streamers WHERE Name=?;", chanName).Scan(&Streamer) switch { case checkStream == sql.ErrNoRows: color.Yellow("No streamer ID, Adding...\n") insertStream, dberr := db.Prepare("INSERT Streamers SET Name=?,StreamID=?;") if dberr != nil { log.Fatalf("Cannot prepare streamer %s, error: %s\n", chanName, dberr.Error()) } defer insertStream.Close() execStream, dberr := insertStream.Exec(chanName, i) if dberr != nil { log.Fatalf("Cannot add streamer %s, error: %s\n", chanName, dberr.Error()) } lastId, dberr := execStream.LastInsertId() if dberr != nil { log.Fatalf("Last id error with streamer %s, error: %s\n", chanName, dberr.Error()) } color.Green("New streamId for %s is #%d, ID = %d\n", k, i, lastId) case checkStream != nil: log.Fatalf("Database query to Streamers table error: %s\n", checkStream.Error()) default: fmt.Printf("#%d: %s, ", Streamer, blue(k)) } } fmt.Printf("\n") }