一个完整的Web服务器

This chapter is principally a lengthy illustration of the HTTP chapter, building a complete Web server in Go. It also shows how to use templates in order to use expressions in text files to insert variable values and to generate repeated sections.

这章主要是针对Http的一个例子,用Go建立一个完整的Web服务器。它也演示了如何在模板中使用表达式在文本文件中插入变量和生成重复的部分。

Introduction

说明

I am learning Chinese. Rather, after many years of trying I am still attempting to learn Chinese. Of course, rather than buckling down and getting on with it, I have tried all sorts of technical aids. I tried DVDs, videos, flashcards and so on. Eventually I realised that there wasn't a good computer program for Chinese flashcards, and so in the interests of learning, I needed to build one.

我正在学习中文,恰恰相反,我已经坚持学习了很多年。当然,为了拿下它,我尝试使用很多技术来帮助我学习中文。其中我尝试过DVD教程,视频教程,快速学习记忆卡等等。但是最后我意识到这里没有一个很好的中文学习记忆卡程序,所以出于学习的兴趣,我需要创建了一个。

I had found a program in Python to do some of the task. But sad to say it wasn't well written and after a few attempts at turning it upside down and inside out I came to the conclusion that it was better to start from scratch. Of course, a Web solution would be far better than a standalone one, because then all the other people in my Chinese class could share it, as well as any other learners out there. And of course, the server would be written in Go.

我发现了一使用Python写的程序可以完成一些这样的任务。但是遗憾的说,它写的不是很好,而且我经过几次尝试捣鼓它,得出一个结论是最好重头开始写一个。当然这个Web解决方案不是我一个人使用,它还会分享给其他学习中文的同学和更多学习中文的者。当然,这个服务我将使用Go语言来写。

The flashcards server is running at cict.bhtafe.edu.au:8000. The front page consists of a list of flashcard sets currently available, how you want a set displayed (random card order, Chinese, English or random), whether to display a set, add to it, etc. I've spent too much time building it - somehow my Chinese hasn't progressed much while I was doing it… It probably won't be too exciting as a program if you don't want to learn Chinese, but let's get into the structure.

flashcards服务器运行在cict.bhtafe.edu.au:8000。在当前页是目前的flashcard组列表,你想怎么显示(随机card的顺序,中文,英文或随机),是否显示一组,还要加上一套,我花了很多时间来构建它 - 不知何故我的中文还没有进展较快,而我该怎么做…它可能不会是太令人兴奋了一个程序,如果你不想学习中文,就让我们来看看程序的结构吧

Static pages

静态文件

Some pages will just have static content. These can be managed by a fileServer. For simplicity I put all of the static HTML pages and CSS files in the html directory and all of the JavaScript files in the jscript directory. These are then delivered by the Go code

有些页面只是一些静态内容。这些可以由FILESERVER管理。为了简单起见,我把所有的静态HTML页面和CSS文件放入html目录中,所有的JavaScript文件放日JScript目录。 然后这些交付给Go代码。

  1. fileServer := http.FileServer("jscript", "/jscript/")
  2. http.Handle("/jscript/", fileServer)
  3. fileServer = http.FileServer("html", "/html/")
  4. http.Handle("/html/", fileServer)

Templates

模板

The list of flashcard sets is open ended, depending on the number of files in a directory. These should not be hardcoded into an HTML page, but the content should be generated as needed. This is an obvious candidate for templates.

flashcard组列表是开放式的, 根据在一个目录中的文件的数量。这些不应该被硬编码到一个HTML页面,但内容应根据需要生成。这就是一个明显的候选模板。

The list of files in a directory is generated as a list of strings. These can then be displayed in a table using the template

目录中的文件列表可以被认为是一个字符串列表。 然后模板可将它们显示在一个表格中。

  1. <table>
  2. {{range .}}
  3. <tr>
  4. <td>
  5. {{.}}
  6. </td>
  7. </tr>
  8. </table>
  9.  

The Chinese Dictionary

中文词典

Chinese is a complex language (aren't they all :-( ). The written form is hieroglyphic, that is "pictograms" instead of using an alphabet. But this written form has evolved over time, and even recently split into two forms: "traditional" Chinese as used in Taiwan and Hong Kong, and "simplified" Chinese as used in mainland China. While most of the characters are the same, about 1,000 are different. Thus a Chinese dictionary will often have two written forms of the same character.

中国是一个复杂的语言(不是所有人:-()。书面形式的象形文字,那是“象形”,而不是使用一个字母,但这个书面形式随着时间的演变,以及最近甚至分裂成两种形式:“繁体”中文使用在中国的台湾和香港,和“简体”中文使用在中国大陆。虽然大多数的文字是相同的,但还是有大约1000中文字是不同的,因此,中文的字典往往有两种书面形式文字。

Most Westerners like me can't understand these characters. So there is a "Latinised" form called Pinyin which writes the characters in a phonetic alphabet based on the Latin alphabet. It isn't quite the Latin alphabet, because Chinese is a tonal language, and the Pinyin form has to show the tones (much like acccents in French and other European languages). So a typical dictionary has to show four things: the traditional form, the simplified form, the Pinyin and the English. For example,

和大多数西方人一样,我无法理解这些字符。所以,有一个“Latinised的形式称为”拼音的字符写入以拉丁字母为基础的拼音第一个字母。这不是拉丁字母,因为这是中文的一种语言音调,和拼音形式显示的音调(很像在法国和其他欧洲语言的acccents)。因此,一个典型的字典有四件事情:繁体形式和简化形式,拼音和英文显示。例如,

Traditional Simplified Pinyin English
hǎo good

But again there is a little complication. There is a free Chinese/English dictionary and even better, you can download it as a UTF-8 file, which Go is well suited to handle. In this, the Chinese characters are written in Unicode but the Pinyin characters are not: although there are Unicode characters for letters such as 'ǎ', many dictionaries including this one use the Latin 'a' and place the tone at the end of the word. Here it is the third tone, so "hǎo" is written as "hao3". This makes it easier for those who only have US keyboards and no Unicode editor to still communicate in Pinyin.

但是还是有点复杂。这里有一个更好的并且免费的中英文词典, 你可以下载它是一个UTF-8的文件,非常适合Go去处理。在这,中文的字符集被写入在Unicode中但是拼音没有:尽管有Unicode字符的字母,如“ǎ”,很多词典包括本使用拉丁字母'a'和将音调放在词的结尾。在这里它是第三个音调,所以“hǎo”被写入“HAO3”。这使得它更容易为那些只有美国键盘和没有Unicode的编辑器的人们来与拼音沟通。

This data format mismatch is not a big deal: just that somewhere along the line, between the original text dictionary and the display in the browser, a data massage has to be performed. Go templates allow this to be done by defining a custom template, so I chose that route. Alternatives could have been to do this as the dictionary is read in, or in the Javascript to display the final characters.

这种数据格式不匹配并不是一个大的问题:只是在这行的某处地方,在原来的文本字典和显示在浏览器之间, 用数据来完成。Go模板允许通过自定义一个模板, 所以我选择了这个思路。可以选择从dictionary中读取,或者由JavaScript来显示最终的字符。

The code for the Pinyin formatter is given below. Please don't bother reading it unless you are really interested in knowing the rules for Pinyin formatting.

拼音格式化的代码在下面给出。请不要仔细的阅读它,除非你真的有兴趣想知道拼音格式化的规则。

  1. package pinyin
  2. import (
  3. "io"
  4. "strings"
  5. )
  6. func PinyinFormatter(w io.Writer, format string, value ...interface{}) {
  7. line := value[0].(string)
  8. words := strings.Fields(line)
  9. for n, word := range words {
  10. // convert "u:" to "ü" if present
  11. uColon := strings.Index(word, "u:")
  12. if uColon != -1 {
  13. parts := strings.SplitN(word, "u:", 2)
  14. word = parts[0] + "ü" + parts[1]
  15. }
  16. println(word)
  17. // get last character, will be the tone if present
  18. chars := []rune(word)
  19. tone := chars[len(chars)-1]
  20. if tone == '5' {
  21. words[n] = string(chars[0 : len(chars)-1])
  22. println("lost accent on", words[n])
  23. continue
  24. }
  25. if tone < '1' || tone > '4' {
  26. continue
  27. }
  28. words[n] = addAccent(word, int(tone))
  29. }
  30. line = strings.Join(words, ` `)
  31. w.Write([]byte(line))
  32. }
  33. var (
  34. // maps 'a1' to '\u0101' etc
  35. aAccent = map[int]rune{
  36. '1': '\u0101',
  37. '2': '\u00e1',
  38. '3': '\u01ce', // '\u0103',
  39. '4': '\u00e0'}
  40. eAccent = map[int]rune{
  41. '1': '\u0113',
  42. '2': '\u00e9',
  43. '3': '\u011b', // '\u0115',
  44. '4': '\u00e8'}
  45. iAccent = map[int]rune{
  46. '1': '\u012b',
  47. '2': '\u00ed',
  48. '3': '\u01d0', // '\u012d',
  49. '4': '\u00ec'}
  50. oAccent = map[int]rune{
  51. '1': '\u014d',
  52. '2': '\u00f3',
  53. '3': '\u01d2', // '\u014f',
  54. '4': '\u00f2'}
  55. uAccent = map[int]rune{
  56. '1': '\u016b',
  57. '2': '\u00fa',
  58. '3': '\u01d4', // '\u016d',
  59. '4': '\u00f9'}
  60. üAccent = map[int]rune{
  61. '1': 'ǖ',
  62. '2': 'ǘ',
  63. '3': 'ǚ',
  64. '4': 'ǜ'}
  65. )
  66. func addAccent(word string, tone int) string {
  67. /*
  68. * Based on "Where do the tone marks go?"
  69. * at http://www.pinyin.info/rules/where.html
  70. */
  71. n := strings.Index(word, "a")
  72. if n != -1 {
  73. aAcc := aAccent[tone]
  74. // replace 'a' with its tone version
  75. word = word[0:n] + string(aAcc) + word[(n+1):len(word)-1]
  76. } else {
  77. n := strings.Index(word, "e")
  78. if n != -1 {
  79. eAcc := eAccent[tone]
  80. word = word[0:n] + string(eAcc) +
  81. word[(n+1):len(word)-1]
  82. } else {
  83. n = strings.Index(word, "ou")
  84. if n != -1 {
  85. oAcc := oAccent[tone]
  86. word = word[0:n] + string(oAcc) + "u" +
  87. word[(n+2):len(word)-1]
  88. } else {
  89. chars := []rune(word)
  90. length := len(chars)
  91. // put tone onthe last vowel
  92. L:
  93. for n, _ := range chars {
  94. m := length - n - 1
  95. switch chars[m] {
  96. case 'i':
  97. chars[m] = iAccent[tone]
  98. break L
  99. case 'o':
  100. chars[m] = oAccent[tone]
  101. break L
  102. case 'u':
  103. chars[m] = uAccent[tone]
  104. break L
  105. case 'ü':
  106. chars[m] = üAccent[tone]
  107. break L
  108. default:
  109. }
  110. }
  111. word = string(chars[0 : len(chars)-1])
  112. }
  113. }
  114. }
  115. return word
  116. }

How this is used is illustrated by the function lookupWord. This is called in response to an HTML Form request to find the English words in a dictionary.

lookupWord函数说明了怎样去使用它。这就是在字典中查找英文单词的Html表单请求的响应。

  1. func lookupWord(rw http.ResponseWriter, req *http.Request) {
  2. word := req.FormValue("word")
  3. words := d.LookupEnglish(word)
  4. pinyinMap := template.FormatterMap {"pinyin": pinyin.PinyinFormatter}
  5. t, err := template.ParseFile("html/DictionaryEntry.html", pinyinMap)
  6. if err != nil {
  7. http.Error(rw, err.String(), http.StatusInternalServerError)
  8. return
  9. }
  10. t.Execute(rw, words)
  11. }

The HTML code is

HTML代码

  1. <html>
  2. <body>
  3. <table border="1">
  4. <tr>
  5. <th>Word</th>
  6. <th>Traditional</th>
  7. <th>Simplified</th>
  8. <th>Pinyin</th>
  9. <th>English</th>
  10. </tr>
  11. {{with .Entries}}
  12. {{range .}}
  13. {.repeated section Entries}
  14. <tr>
  15. <td>{{.Word}}</td>
  16. <td>{{.Traditional}}</td>
  17. <td>{{.Simplified}}</td>
  18. <td>{{.Pinyin|pinyin}}</td>
  19. <td>
  20. <pre>
  21. {.repeated section Translations}
  22. {@|html}
  23. {.end}
  24. </pre>
  25. </td>
  26. </tr>
  27. {.end}
  28. {{end}}
  29. {{end}}
  30. </table>
  31. </body>
  32. </html>

The Dictionary type

字典类型

The text file containing the dictionary has lines of the form

traditional simplified [pinyin] /translation/translation/…/

For example,

好 好 [hao3] /good/well/proper/good to/easy to/very/so/(suffix indicating completion or readiness)/

字典中的文本文件中一行的格式

繁体 简体 [拼音] /翻译/翻译/…/

例如,

好 好 [hao3] /good/well/proper/good to/easy to/very/so/(suffix indicating completion or readiness)/

We store each line as an Entry within the Dictionary package:

我们的Dictionary包里存储的一行Entry

  1. type Entry struct {
  2. Traditional string
  3. Simplified string
  4. Pinyin string
  5. Translations []string
  6. }

The dictionary itself is just an array of these entries:

字典本身只是一个entry的数组:

  1. type Dictionary struct {
  2. Entries []*Entry
  3. }

Building the dictionary is easy enough. Just read each line and break the line into its various bits using simple string methods. Then add the line to the dictionary slice.

构建字典是很容易的。只要使用简单的字符串方法读取一行然后进行分割。最后添加到dictionary slice中。

Looking up entries in this dictionary is straightforward: just search through until we find the appropriate key. There are about 100,000 entries in this dictionary: brute force by a linear search is fast enough. If it were necessary, faster storage and search mechanisms could easily be used.

在这本词典中查找条目非常简单:只要通过搜索直到我们找到合适的答案。在这本字典有10万左右的条目:暴力的线性搜索速度不够快。如果有必要,可以使用更快的存储和搜索机制。

The original dictionary grows by people on the Web adding in entries as they see fit. Consequently it isn't that well organised and contains repetitions and multiple entries. So looking up any word - either by Pinyin or by English - may return multiple matches. To cater for this, each lookup returns a "mini dictionary", just those lines in the full dictionary that match.

原词典发展的人添加条目他们认为网络更适合。所以它不是有条理的和包含了多个重复的条目。因此查找任何单词 - 无论是通过拼音或英语 - 可能返回多个匹配。为了应付这个问题,每个查询返回一个“mini dictionary”,只有那些在字典中匹配的。

The Dictionary code is

Dictionary 代码

  1. package dictionary
  2. import (
  3. "bufio"
  4. //"fmt"
  5. "os"
  6. "strings"
  7. )
  8. type Entry struct {
  9. Traditional string
  10. Simplified string
  11. Pinyin string
  12. Translations []string
  13. }
  14. func (de Entry) String() string {
  15. str := de.Traditional + ` ` + de.Simplified + ` ` + de.Pinyin
  16. for _, t := range de.Translations {
  17. str = str + "\n " + t
  18. }
  19. return str
  20. }
  21. type Dictionary struct {
  22. Entries []*Entry
  23. }
  24. func (d *Dictionary) String() string {
  25. str := ""
  26. for n := 0; n < len(d.Entries); n++ {
  27. de := d.Entries[n]
  28. str += de.String() + "\n"
  29. }
  30. return str
  31. }
  32. func (d *Dictionary) LookupPinyin(py string) *Dictionary {
  33. newD := new(Dictionary)
  34. v := make([]*Entry, 0, 100)
  35. for n := 0; n < len(d.Entries); n++ {
  36. de := d.Entries[n]
  37. if de.Pinyin == py {
  38. v = append(v, de)
  39. }
  40. }
  41. newD.Entries = v
  42. return newD
  43. }
  44. func (d *Dictionary) LookupEnglish(eng string) *Dictionary {
  45. newD := new(Dictionary)
  46. v := make([]*Entry, 0, 100)
  47. for n := 0; n < len(d.Entries); n++ {
  48. de := d.Entries[n]
  49. for _, e := range de.Translations {
  50. if e == eng {
  51. v = append(v, de)
  52. }
  53. }
  54. }
  55. newD.Entries = v
  56. return newD
  57. }
  58. func (d *Dictionary) LookupSimplified(simp string) *Dictionary {
  59. newD := new(Dictionary)
  60. v := make([]*Entry, 0, 100)
  61. for n := 0; n < len(d.Entries); n++ {
  62. de := d.Entries[n]
  63. if de.Simplified == simp {
  64. v = append(v, de)
  65. }
  66. }
  67. newD.Entries = v
  68. return newD
  69. }
  70. func (d *Dictionary) Load(path string) {
  71. f, err := os.Open(path)
  72. r := bufio.NewReader(f)
  73. if err != nil {
  74. println(err.Error())
  75. os.Exit(1)
  76. }
  77. v := make([]*Entry, 0, 100000)
  78. numEntries := 0
  79. for {
  80. line, err := r.ReadString('\n')
  81. if err != nil {
  82. break
  83. }
  84. if line[0] == '#' {
  85. continue
  86. }
  87. // fmt.Println(line)
  88. trad, simp, pinyin, translations := parseDictEntry(line)
  89. de := Entry{
  90. Traditional: trad,
  91. Simplified: simp,
  92. Pinyin: pinyin,
  93. Translations: translations}
  94. v = append(v, &de)
  95. numEntries++
  96. }
  97. // fmt.Printf("Num entries %d\n", numEntries)
  98. d.Entries = v
  99. }
  100. func parseDictEntry(line string) (string, string, string, []string) {
  101. // format is
  102. // trad simp [pinyin] /trans/trans/.../
  103. tradEnd := strings.Index(line, " ")
  104. trad := line[0:tradEnd]
  105. line = strings.TrimSpace(line[tradEnd:])
  106. simpEnd := strings.Index(line, " ")
  107. simp := line[0:simpEnd]
  108. line = strings.TrimSpace(line[simpEnd:])
  109. pinyinEnd := strings.Index(line, "]")
  110. pinyin := line[1:pinyinEnd]
  111. line = strings.TrimSpace(line[pinyinEnd+1:])
  112. translations := strings.Split(line, "/")
  113. // includes empty at start and end, so
  114. translations = translations[1 : len(translations)-1]
  115. return trad, simp, pinyin, translations
  116. }

Flash cards

Flash cards

Each individual flash card is of the type Flashcard

每个flash card的类型Flashcard

  1. type FlashCard struct {
  2. Simplified string
  3. English string
  4. Dictionary *dictionary.Dictionary
  5. }
  6.  

At present we only store the simplified character and the english translation for that character. We also have a Dictionary which will contain only one entry for the entry we will have chosen somewhere.

目前我们只存储简体字符和该字符的英文翻译。我们将有选择性的加入一个entry到这里的Dictionary中。

A set of flash cards is defined by the type

flash cards组的类型

  1. type FlashCards struct {
  2. Name string
  3. CardOrder string
  4. ShowHalf string
  5. Cards []*FlashCard
  6. }
  7.  

where the CardOrder will be "random" or "sequential" and the ShowHalf will be "RANDOM_HALF" or "ENGLISH_HALF" or "CHINESE_HALF" to determine which half of a new card is shown first.

其中CardOrder将是“random”或者“sequential”和ShowHalf将是“RANDOM_HALF”或“ENGLISH_HALF”或的“CHINESE_HALF”来确定一个新的卡中,意思是中文和英文其中有一个首先被显示。

The code for flash cards has nothing novel in it. We get data from the client browser and use JSON to create an object from the form data, and store the set of flashcards as a JSON string.

flash cards的代码并没有新意。我们从浏览器客户端获取数据并根据表单的数据使用JSON来创建一个对象,并将其存储于flashcards中作为一个JSON字符串。

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. }

Other Bits: JavaScript and CSS

其他: JavaScript 和 CSS

On request, a set of flashcards will be loaded into the browser. A much abbreviated set is shown below. The display of these cards is controlled by JavaScript and CSS files. These aren't relevant to the Go server so are omitted. Those interested can download the code.

根据需求,flashcards组将会被加载到浏览器中。下面展示了一个简短的HTML页。cards的显示由JavaScript和CSS文件控制。这些都不是和Go服务器相关的技术所以在这省略了。有兴趣的可以下载代码。

  1. <html>
  2. <head>
  3. <title>
  4. Flashcards for Common Words
  5. </title>
  6. <link type="text/css" rel="stylesheet"
  7. href="/html/CardStylesheet.css">
  8. </link>
  9. <script type="text/javascript"
  10. language="JavaScript1.2" src="/jscript/jquery.js">
  11. <!-- empty -->
  12. </script>
  13. <script type="text/javascript"
  14. language="JavaScript1.2" src="/jscript/slideviewer.js">
  15. <!-- empty -->
  16. </script>
  17. <script type="text/javascript"
  18. language="JavaScript1.2">
  19. cardOrder = RANDOM;
  20. showHalfCard = RANDOM_HALF;
  21. </script>
  22. </head>
  23. <body onload="showSlides();">
  24. <h1>
  25. Flashcards for Common Words
  26. </h1>
  27. <p>
  28. <div class="card">
  29. <div class="english">
  30. <div class="vcenter">
  31. hello
  32. </div>
  33. </div>
  34. <div class="pinyin">
  35. <div class="vcenter">
  36. nǐ hǎo
  37. </div>
  38. </div>
  39. <div class="traditional">
  40. <div class="vcenter">
  41. 你好
  42. </div>
  43. </div>
  44. <div class="simplified">
  45. <div class="vcenter">
  46. 你好
  47. </div>
  48. </div>
  49. <div class ="translations">
  50. <div class="vcenter">
  51. hello <br />
  52. hi <br />
  53. how are you? <br />
  54. </div>
  55. </div>
  56. </div>
  57. <div class="card">
  58. <div class="english">
  59. <div class="vcenter">
  60. hello (interj., esp. on telephone)
  61. </div>
  62. </div>
  63. <div class="pinyin">
  64. <div class="vcenter">
  65. wèi
  66. </div>
  67. </div>
  68. <div class="traditional">
  69. <div class="vcenter">
  70. </div>
  71. </div>
  72. <div class="simplified">
  73. <div class="vcenter">
  74. </div>
  75. </div>
  76. <div class ="translations">
  77. <div class="vcenter">
  78. hello (interj., esp. on telephone) <br />
  79. hey <br />
  80. to feed (sb or some animal) <br />
  81. </div>
  82. </div>
  83. </div>
  84. </p>
  85. <p class ="return">
  86. Press <Space> to continue
  87. <br/>
  88. <a href="http:/flashcards.html"> Return to Flash Cards list</a>
  89. </p>
  90. </body>
  91. </html>

Copyright Jan Newmarch, jan@newmarch.name

版权所有 Jan Newmarch, jan@newmarch.name

If you like this book, please contribute using Flattr

or donate using PayPal

一个完整的Web服务器 - 图1