github.com/bcampbell/scrapeomat@v0.0.0-20220820232205-23e64141c89e/cmd/slurpserver/count.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	//	"github.com/bcampbell/scrapeomat/store"
     8  )
     9  
    10  type ArticleCountResult struct {
    11  	ArticleCount int `json:"article_count"`
    12  }
    13  
    14  // implement api/count
    15  func (srv *SlurpServer) countHandler(ctx *Context, w http.ResponseWriter, r *http.Request) {
    16  
    17  	filt, err := getFilter(r)
    18  	if err != nil {
    19  		http.Error(w, err.Error(), 400)
    20  		return
    21  	}
    22  
    23  	totalArts, err := srv.db.FetchCount(filt)
    24  	if err != nil {
    25  		// TODO: should send error via json?
    26  		http.Error(w, fmt.Sprintf("DB error: %s", err), 500)
    27  		return
    28  	}
    29  
    30  	msg := ArticleCountResult{ArticleCount: totalArts}
    31  	outBuf, err := json.Marshal(msg)
    32  	if err != nil {
    33  		errMsg := fmt.Sprintf("json encoding error: %s\n", err)
    34  		srv.ErrLog.Printf(errMsg)
    35  		http.Error(w, errMsg, 500)
    36  		return
    37  	}
    38  	_, err = w.Write(outBuf)
    39  	if err != nil {
    40  		srv.ErrLog.Printf("write error: %s\n", err)
    41  		return
    42  	}
    43  
    44  	srv.InfoLog.Printf("%s /api/count OK %d arts %s\n", r.RemoteAddr, totalArts, filt.Describe())
    45  }