@@ -357,6 +357,13 @@ func newTemplate(files ...string) *template.Template {
357357	return  template .Must (t .ParseFS (embeddedFS , tf ... ))
358358}
359359
360+ // initMetrics initialize Prometheus Metrics 
361+ func  initMetrics () {
362+ 	prometheus .MustRegister (clickCounter )
363+ 	prometheus .MustRegister (clickNotFound )
364+ 	prometheus .MustRegister (totalLinkCount )
365+ }
366+ 
360367// initStats initializes the in-memory stats counter with counts from db. 
361368func  initStats () error  {
362369	stats .mu .Lock ()
@@ -370,6 +377,14 @@ func initStats() error {
370377	stats .clicks  =  clicks 
371378	stats .dirty  =  make (ClickStats )
372379
380+ 	// Set the totalLinkCount metric to what is saved in the DB 
381+ 	var  count  float64 
382+ 	err  =  db .db .QueryRow ("SELECT COUNT(DISTINCT id) FROM Links" ).Scan (& count )
383+ 	if  err  !=  nil  {
384+ 		return  err 
385+ 	}
386+ 	totalLinkCount .Set (count )
387+ 
373388	return  nil 
374389}
375390
@@ -444,13 +459,6 @@ func HSTS(h http.Handler) http.Handler {
444459	})
445460}
446461
447- // initMetrics initializes prometheus metrics. 
448- func  initMetrics () {
449- 	prometheus .MustRegister (clickCounter )
450- 	prometheus .MustRegister (totalLinkCount )
451- 	prometheus .MustRegister (clickNotFound )
452- }
453- 
454462// serverHandler returns the main http.Handler for serving all requests. 
455463func  serveHandler () http.Handler  {
456464	mux  :=  http .NewServeMux ()
@@ -959,11 +967,13 @@ func serveSave(w http.ResponseWriter, r *http.Request) {
959967	}
960968
961969	now  :=  time .Now ().UTC ()
970+ 	newLink  :=  false 
962971	if  link  ==  nil  {
963972		link  =  & Link {
964973			Short :   short ,
965974			Created : now ,
966975		}
976+ 		newLink  =  true 
967977	}
968978	link .Short  =  short 
969979	link .Long  =  long 
@@ -980,7 +990,10 @@ func serveSave(w http.ResponseWriter, r *http.Request) {
980990		w .Header ().Set ("Content-Type" , "application/json" )
981991		json .NewEncoder (w ).Encode (link )
982992	}
983- 	totalLinkCount .Inc ()
993+ 	// If this is a new link and not an update inc 
994+ 	if  newLink  {
995+ 		totalLinkCount .Inc ()
996+ 	}
984997}
985998
986999// canEditLink returns whether the specified user has permission to edit link. 
0 commit comments