Golang : Check from web if Go application is running or not
When we run some processes in the background to perform certain tasks and it would be a good idea to know if the process is still alive and kicking from time to time.
In this tutorial, we will learn how to check if a Golang program is still running in the memory and also spit out some custom information with a web browser.
In this example, our program will inform the world that it is running fine if everything is ok and reply with the total number of processes running in memory. Please change the code below to suit your requirements.
Run this code below and then point your browser to http://localhost:8088
and http://localhost:8088/getstatus
(case sensitive) to see the output
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os/exec"
)
func Greet(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello! I'm the getstatus.go program and I'm still alive and kicking."))
}
func ReplyStatus(w http.ResponseWriter, r *http.Request) {
// taken from
// https://www.socketloop.com/tutorials/golang-pipe-output-from-one-os-exec-shell-command-to-another-command
first := exec.Command("ps", "-ef")
second := exec.Command("wc", "-l")
reader, writer := io.Pipe()
first.Stdout = writer
second.Stdin = reader
var buff bytes.Buffer
second.Stdout = &buff
first.Start()
second.Start()
first.Wait()
writer.Close()
second.Wait()
total := buff.String() // convert output to string
w.Write([]byte(fmt.Sprintf("Total processes running on this server : %s ", total)))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", Greet)
mux.HandleFunc("/getstatus", ReplyStatus)
http.ListenAndServe(":8088", mux)
}
NOTE : In a production system..... because the program is accessible from the web(outside world), you need to add some security measure such as password(with TFA) protected page or only accept incoming request from certain IP address.
References :
https://www.socketloop.com/tutorials/golang-gorilla-mux-routing-example
https://www.socketloop.com/tutorials/golang-web-routing-multiplex-example
See also : Golang : Web routing/multiplex example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+36.1k Golang : Convert(cast) int64 to string
+32.3k Golang : Regular Expression for alphanumeric and underscore
+29.9k Golang : How to verify uploaded file is image or allowed file types
+11.1k Golang : Post data with url.Values{}
+51.6k Golang : How to get time in milliseconds?
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+9.8k Golang : Bcrypting password
+7.3k Golang : Mapping Iban to Dunging alphabets
+6k Apt-get to install and uninstall Golang
+20.8k Golang : Create and resolve(read) symbolic links