The Complete Server

The complete server is

  1. /* Server
  2. */
  3. package main
  4. import (
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "regexp"
  10. "text/template"
  11. )
  12. import (
  13. "dictionary"
  14. "flashcards"
  15. "templatefuncs"
  16. )
  17. var d *dictionary.Dictionary
  18. func main() {
  19. if len(os.Args) != 2 {
  20. fmt.Fprint(os.Stderr, "Usage: ", os.Args[0], ":port\n")
  21. os.Exit(1)
  22. }
  23. port := os.Args[1]
  24. // dictionaryPath := "/var/www/go/chinese/cedict_ts.u8"
  25. dictionaryPath := "cedict_ts.u8"
  26. d = new(dictionary.Dictionary)
  27. d.Load(dictionaryPath)
  28. fmt.Println("Loaded dict", len(d.Entries))
  29. http.HandleFunc("/", listFlashCards)
  30. //fileServer := http.FileServer("/var/www/go/chinese/jscript", "/jscript/")
  31. fileServer := http.StripPrefix("/jscript/", http.FileServer(http.Dir("jscript")))
  32. http.Handle("/jscript/", fileServer)
  33. // fileServer = http.FileServer("/var/www/go/chinese/html", "/html/")
  34. fileServer = http.StripPrefix("/html/", http.FileServer(http.Dir("html")))
  35. http.Handle("/html/", fileServer)
  36. http.HandleFunc("/wordlook", lookupWord)
  37. http.HandleFunc("/flashcards.html", listFlashCards)
  38. http.HandleFunc("/flashcardSets", manageFlashCards)
  39. http.HandleFunc("/searchWord", searchWord)
  40. http.HandleFunc("/addWord", addWord)
  41. http.HandleFunc("/newFlashCardSet", newFlashCardSet)
  42. // deliver requests to the handlers
  43. err := http.ListenAndServe(port, nil)
  44. checkError(err)
  45. // That's it!
  46. }
  47. func indexPage(rw http.ResponseWriter, req *http.Request) {
  48. index, _ := ioutil.ReadFile("html/index.html")
  49. rw.Write([]byte(index))
  50. }
  51. func lookupWord(rw http.ResponseWriter, req *http.Request) {
  52. word := req.FormValue("word")
  53. words := d.LookupEnglish(word)
  54. //t := template.New("PinyinTemplate")
  55. t := template.New("DictionaryEntry.html")
  56. t = t.Funcs(template.FuncMap{"pinyin": templatefuncs.PinyinFormatter})
  57. t, err := t.ParseFiles("html/DictionaryEntry.html")
  58. if err != nil {
  59. http.Error(rw, err.Error(), http.StatusInternalServerError)
  60. return
  61. }
  62. t.Execute(rw, words)
  63. }
  64. type DictPlus struct {
  65. *dictionary.Dictionary
  66. Word string
  67. CardName string
  68. }
  69. func searchWord(rw http.ResponseWriter, req *http.Request) {
  70. word := req.FormValue("word")
  71. searchType := req.FormValue("searchtype")
  72. cardName := req.FormValue("cardname")
  73. var words *dictionary.Dictionary
  74. var dp []DictPlus
  75. if searchType == "english" {
  76. words = d.LookupEnglish(word)
  77. d1 := DictPlus{Dictionary: words, Word: word, CardName: cardName}
  78. dp = make([]DictPlus, 1)
  79. dp[0] = d1
  80. } else {
  81. words = d.LookupPinyin(word)
  82. numTrans := 0
  83. for _, entry := range words.Entries {
  84. numTrans += len(entry.Translations)
  85. }
  86. dp = make([]DictPlus, numTrans)
  87. idx := 0
  88. for _, entry := range words.Entries {
  89. for _, trans := range entry.Translations {
  90. dict := new(dictionary.Dictionary)
  91. dict.Entries = make([]*dictionary.Entry, 1)
  92. dict.Entries[0] = entry
  93. dp[idx] = DictPlus{
  94. Dictionary: dict,
  95. Word: trans,
  96. CardName: cardName}
  97. idx++
  98. }
  99. }
  100. }
  101. //t := template.New("PinyinTemplate")
  102. t := template.New("ChooseDictionaryEntry.html")
  103. t = t.Funcs(template.FuncMap{"pinyin": templatefuncs.PinyinFormatter})
  104. t, err := t.ParseFiles("html/ChooseDictionaryEntry.html")
  105. if err != nil {
  106. fmt.Println(err.Error())
  107. http.Error(rw, err.Error(), http.StatusInternalServerError)
  108. return
  109. }
  110. t.Execute(rw, dp)
  111. }
  112. func newFlashCardSet(rw http.ResponseWriter, req *http.Request) {
  113. defer http.Redirect(rw, req, "http:/flashcards.html", 200)
  114. newSet := req.FormValue("NewFlashcard")
  115. fmt.Println("New cards", newSet)
  116. // check against nasties:
  117. b, err := regexp.Match("[/$~]", []byte(newSet))
  118. if err != nil {
  119. return
  120. }
  121. if b {
  122. fmt.Println("No good string")
  123. return
  124. }
  125. flashcards.NewFlashCardSet(newSet)
  126. return
  127. }
  128. func addWord(rw http.ResponseWriter, req *http.Request) {
  129. url := req.URL
  130. fmt.Println("url", url.String())
  131. fmt.Println("query", url.RawQuery)
  132. word := req.FormValue("word")
  133. cardName := req.FormValue("cardname")
  134. simplified := req.FormValue("simplified")
  135. pinyin := req.FormValue("pinyin")
  136. traditional := req.FormValue("traditional")
  137. translations := req.FormValue("translations")
  138. fmt.Println("word is ", word, " card is ", cardName,
  139. " simplified is ", simplified, " pinyin is ", pinyin,
  140. " trad is ", traditional, " trans is ", translations)
  141. flashcards.AddFlashEntry(cardName, word, pinyin, simplified,
  142. traditional, translations)
  143. // add another card?
  144. addFlashCards(rw, cardName)
  145. }
  146. func listFlashCards(rw http.ResponseWriter, req *http.Request) {
  147. flashCardsNames := flashcards.ListFlashCardsNames()
  148. t, err := template.ParseFiles("html/ListFlashcards.html")
  149. if err != nil {
  150. http.Error(rw, err.Error(), http.StatusInternalServerError)
  151. return
  152. }
  153. t.Execute(rw, flashCardsNames)
  154. }
  155. /*
  156. * Called from ListFlashcards.html on form submission
  157. */
  158. func manageFlashCards(rw http.ResponseWriter, req *http.Request) {
  159. set := req.FormValue("flashcardSets")
  160. order := req.FormValue("order")
  161. action := req.FormValue("submit")
  162. half := req.FormValue("half")
  163. fmt.Println("set chosen is", set)
  164. fmt.Println("order is", order)
  165. fmt.Println("action is", action)
  166. cardname := "flashcardSets/" + set
  167. //components := strings.Split(req.URL.Path[1:], "/", -1)
  168. //cardname := components[1]
  169. //action := components[2]
  170. fmt.Println("cardname", cardname, "action", action)
  171. if action == "Show cards in set" {
  172. showFlashCards(rw, cardname, order, half)
  173. } else if action == "List words in set" {
  174. listWords(rw, cardname)
  175. } else if action == "Add cards to set" {
  176. addFlashCards(rw, set)
  177. }
  178. }
  179. func showFlashCards(rw http.ResponseWriter, cardname, order, half string) {
  180. fmt.Println("Loading card name", cardname)
  181. cards := new(flashcards.FlashCards)
  182. //cards.Load(cardname, d)
  183. //flashcards.SaveJSON(cardname + ".json", cards)
  184. flashcards.LoadJSON(cardname, &cards)
  185. if order == "Sequential" {
  186. cards.CardOrder = "SEQUENTIAL"
  187. } else {
  188. cards.CardOrder = "RANDOM"
  189. }
  190. fmt.Println("half is", half)
  191. if half == "Random" {
  192. cards.ShowHalf = "RANDOM_HALF"
  193. } else if half == "English" {
  194. cards.ShowHalf = "ENGLISH_HALF"
  195. } else {
  196. cards.ShowHalf = "CHINESE_HALF"
  197. }
  198. fmt.Println("loaded cards", len(cards.Cards))
  199. fmt.Println("Card name", cards.Name)
  200. //t := template.New("PinyinTemplate")
  201. t := template.New("ShowFlashcards.html")
  202. t = t.Funcs(template.FuncMap{"pinyin": templatefuncs.PinyinFormatter})
  203. t, err := t.ParseFiles("html/ShowFlashcards.html")
  204. if err != nil {
  205. fmt.Println(err.Error())
  206. http.Error(rw, err.Error(), http.StatusInternalServerError)
  207. return
  208. }
  209. err = t.Execute(rw, cards)
  210. if err != nil {
  211. fmt.Println("Execute error " + err.Error())
  212. http.Error(rw, err.Error(), http.StatusInternalServerError)
  213. return
  214. }
  215. }
  216. func listWords(rw http.ResponseWriter, cardname string) {
  217. fmt.Println("Loading card name", cardname)
  218. cards := new(flashcards.FlashCards)
  219. //cards.Load(cardname, d)
  220. flashcards.LoadJSON(cardname, cards)
  221. fmt.Println("loaded cards", len(cards.Cards))
  222. fmt.Println("Card name", cards.Name)
  223. //t := template.New("PinyinTemplate")
  224. t := template.New("ListWords.html")
  225. if t.Tree == nil || t.Root == nil {
  226. fmt.Println("New t is an incomplete or empty template")
  227. }
  228. t = t.Funcs(template.FuncMap{"pinyin": templatefuncs.PinyinFormatter})
  229. t, err := t.ParseFiles("html/ListWords.html")
  230. if t.Tree == nil || t.Root == nil {
  231. fmt.Println("Parsed t is an incomplete or empty template")
  232. }
  233. if err != nil {
  234. fmt.Println("Parse error " + err.Error())
  235. http.Error(rw, err.Error(), http.StatusInternalServerError)
  236. return
  237. }
  238. err = t.Execute(rw, cards)
  239. if err != nil {
  240. fmt.Println("Execute error " + err.Error())
  241. http.Error(rw, err.Error(), http.StatusInternalServerError)
  242. return
  243. }
  244. fmt.Println("No error ")
  245. }
  246. func addFlashCards(rw http.ResponseWriter, cardname string) {
  247. t, err := template.ParseFiles("html/AddWordToSet.html")
  248. if err != nil {
  249. fmt.Println("Parse error " + err.Error())
  250. http.Error(rw, err.Error(), http.StatusInternalServerError)
  251. return
  252. }
  253. cards := flashcards.GetFlashCardsByName(cardname, d)
  254. t.Execute(rw, cards)
  255. if err != nil {
  256. fmt.Println("Execute error " + err.Error())
  257. http.Error(rw, err.Error(), http.StatusInternalServerError)
  258. return
  259. }
  260. }
  261. func checkError(err error) {
  262. if err != nil {
  263. fmt.Println("Fatal error ", err.Error())
  264. os.Exit(1)
  265. }
  266. }