Refactor into a few files. Add web service JSON query support.
[quanweb.git] / main / handler.go
1 package main
2
3 import (
4   "encoding/json"
5   "fmt"
6   "net/http"
7   "strconv"
8   "strings"
9 )
10
11 const PARAM_IDS = "ids"
12 const MAX_TERMS = 10
13
14 // ============================================================================
15 func handler(w http.ResponseWriter, r *http.Request) {
16   err := r.ParseForm()
17   if nil != err {
18     fmt.Fprintln(w, "ERROR!", err)
19     return
20   }
21
22   action := r.URL.Path[1:]
23
24   switch(action) {
25   case "info":
26     handleInfo(w, r)
27   case "search":
28     handleSearch(w, r)
29   default:
30     fmt.Fprintf(w, "Unrecognized request:  %s\n", r.URL.Path[1:])
31     fmt.Fprintf(w, "id: %s\n", r.FormValue("id"))
32   
33     fmt.Fprintln(w, "URL: ", r.URL)
34     fmt.Fprintln(w, "Query: ", r.URL.Query())
35   }
36 }
37
38 func handleInfo(w http.ResponseWriter, r *http.Request) {
39   idParams := r.Form[PARAM_IDS]
40   if 1 != len(idParams) {
41     fmt.Fprintln(w, "ERROR!  Detected either zero or multiple ids= parameters.  Exactly one expected.")
42     return 
43   } 
44
45   idParam := idParams[0]
46   idStrings := strings.Split(idParam, ",")
47   ids := make([]int, len(idStrings))
48   for i, v := range(idStrings) {
49     var err error
50     ids[i], err = strconv.Atoi(v)
51     if nil != err {
52       ids[i] = 0
53     }
54   }
55
56   books := queryBooksByIds(ids)
57
58   var jsonValue []byte
59   var err error
60   jsonValue, err = json.Marshal(books)
61   if nil != err {
62     fmt.Fprintln(w, "ERROR!", err)
63   } else {
64     w.Write(jsonValue)
65   }
66 }
67
68 func handleSearch(w http.ResponseWriter, r *http.Request) {
69   fields := []Field{Author, Title, Series}
70
71   terms := make([]SearchTerm, len(fields))
72   
73   count := 0
74   for _, fv := range(fields) {
75     paramName := fv.String()
76     paramValues := r.Form[paramName]
77     for _, pv := range(paramValues) {
78       if count >= len(terms) {
79         fmt.Printf("WARNING:  limit of %v search terms exceeded.  One or more terms ignored.")
80         break
81       }
82       terms[count] = SearchTerm{Attribute:fv, Text:pv}
83       count++
84     }
85   }
86
87   terms = terms[:count]
88
89   ids := queryIds(terms)
90
91   jsonValue, err := json.Marshal(ids)
92   if nil != err {
93     fmt.Fprintln(w, "ERROR!", err)
94   } else {
95     w.Write(jsonValue)
96   }
97 }