Infinite Loop: keep printing a single line

Viewed 442

There's an infinite loop that will call a function() every 5 seconds. According to certain conditions, the function() will either print OK or Not Ok.

Here's my code:

package main

import (
    "fmt"
    "time"
    "net/http"
)

func main() {
    
    for {
        dummy()
        time.Sleep(5 * time.Second)
    }
}

func dummy() {
    resp, _ := http.Get("dummy.test.com")
    
    if resp.StatusCode == 200 {
        fmt.Println("OK")
    } else {
        fmt.Println("Not OK.")
    }   
}

Instead of printing:

OK
OK
OK
...

or vice versa, I want a single line to be printed, like so:

OK

And when the function() re-executes after 5 seconds, I want the data that's about to be printed to replace the previous printed data on the same line.

Can someone point me in the right direction ?

2 Answers

You need to print the carriage return character \r for this which you can't to with Println. Suggest using Printf instead

fmt.Printf("\r%s", "OK")

Try this :

package main

import (
    "fmt"
    "time"
    "net/http"
)

func main() {
    
    for {
        result := dummy()
        fmt.Println(result)
        time.Sleep(5 * time.Second)
    }
}

func dummy() string {
    resp, _ := http.Get("dummy.test.com")
    
    if resp.StatusCode == 200 {
        return "OK"
    } else {
        return "Not Ok!"
    }
    
}
Related