github.com/bcampbell/scrapeomat@v0.0.0-20220820232205-23e64141c89e/cmd/slurpserver/browse.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "github.com/bcampbell/scrapeomat/store" 6 "html/template" 7 "net/http" 8 "os" 9 "strconv" 10 ) 11 12 func (srv *SlurpServer) browseHandler(w http.ResponseWriter, r *http.Request) { 13 14 ctx := &Context{Prefix: srv.Prefix} 15 16 filt, err := getFilter(r) 17 if err != nil { 18 http.Error(w, err.Error(), 400) 19 return 20 } 21 22 filt.Count = 100 23 24 pubs, err := srv.db.FetchPublications() 25 if err != nil { 26 http.Error(w, fmt.Sprintf("FetchPublications error: %s", err), 500) 27 return 28 } 29 30 it := srv.db.Fetch(filt) 31 defer it.Close() 32 arts := []*store.Article{} 33 for it.Next() { 34 arts = append(arts, it.Article()) 35 } 36 if it.Err() != nil { 37 http.Error(w, fmt.Sprintf("Fetch error: %s", it.Err()), 500) 38 return 39 } 40 41 // 42 highID := 0 43 for _, art := range arts { 44 if art.ID > highID { 45 highID = art.ID 46 } 47 } 48 49 // set up url to grab next batch 50 nextFilt := Filter(*filt) 51 nextFilt.SinceID = highID 52 nextFilt.Count = 0 53 54 params := struct { 55 Ctx *Context 56 Filt *Filter 57 Pubs []store.Publication 58 Arts []*store.Article 59 MoreURL template.URL 60 }{ 61 ctx, 62 (*Filter)(filt), 63 pubs, 64 arts, 65 template.URL("?" + nextFilt.Params().Encode()), 66 } 67 68 err = srv.tmpls.browse.Execute(w, params) 69 if err != nil { 70 fmt.Fprintf(os.Stderr, "template error: %s", err) 71 return 72 } 73 } 74 75 // display a single article 76 func (srv *SlurpServer) artHandler(w http.ResponseWriter, r *http.Request) { 77 fmt.Printf("id=%s\n", r.FormValue("id")) 78 if r.FormValue("id") == "" { 79 http.Error(w, "Not found", 404) 80 return 81 } 82 83 artID, err := strconv.Atoi(r.FormValue("id")) 84 if err != nil { 85 http.Error(w, "Not found", 404) 86 return 87 } 88 89 art, err := srv.db.FetchArt(artID) 90 if err != nil { 91 http.Error(w, err.Error(), 500) 92 return 93 } 94 ctx := &Context{Prefix: srv.Prefix} 95 96 params := struct { 97 Ctx *Context 98 Art *store.Article 99 }{ 100 ctx, 101 art, 102 } 103 104 err = srv.tmpls.art.Execute(w, params) 105 if err != nil { 106 fmt.Fprintf(os.Stderr, "template error: %s", err) 107 return 108 } 109 }