// Implement chinese.ToHTMLer func (r Record) ToHTML(toneColors []string) string { var html string html += r.Trad html += " " html += pinyin.Num2DiaCol(r.Pinyin, toneColors, " ") html += " " html += r.English return html }
// This function is responsible for paths of the form // /vocab/lookup/<word> and returns a json dictionary // containing the csv to be added to the output text area // or an "error" field of something other than "nil" if an // error occured during execution. func vocabLookupHandler(writer http.ResponseWriter, request *http.Request) { word := getLastPathComponent(request) colors := getColors(request) fmt.Println("vocabLookupHandler: " + word) // search the db for records (simp first, if unsuccessful, try trad) // and send errors back to client if any occur records, err := cedict.FindRecords(word, chinese.Simp) if err != nil { fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`) return } if len(records) == 0 { records, err = cedict.FindRecords(word, chinese.Trad) if err != nil { fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`) return } } if len(records) == 0 { fmt.Fprint(writer, `{"error": "No matches found", "word": "`+word+`"}`) return } // this string has the same number of characters as the word. // in places where the simplified and the traditional characters // are the same, it has a space, otherwise it has the simplified character simpChars := "" tradChars := "" for is, cs := range records[0].Simp { for it, ct := range records[0].Trad { if is == it { if cs == ct { simpChars += string('\u3000') tradChars += string('\u3000') } else { simpChars += string(cs) tradChars += string(ct) } } } } // construct csv row var output string output += records[0].Trad output += "\t" output += records[0].Simp output += "\t" // This dot is necessary because Anki trims whitespace when importing. // For more details, see the card layout of the shengci deck output += "." + tradChars output += "\t" output += "." + simpChars output += "\t" for _, record := range records { output += pinyin.Num2DiaCol(record.Pinyin, colors, " ") // Add another real space character at the end // to make the line break between pinyin and definition on small screens output += " " output += record.English output += "<br />" } // use json.Marshal with an anonymous variable to escape the \t and " characters // in the response j, err := json.Marshal(map[string]interface{}{ "error": "nil", "csv": output, }) if err != nil { fmt.Fprint(writer, `{"error": "`+err.Error()+`", "word": "`+word+`"}`) return } fmt.Fprint(writer, string(j)) }