Created
January 24, 2021 06:24
-
-
Save mikkkee/4b919b917a496e60764d62c0b9339703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package p contains an HTTP Cloud Function. | |
package p | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"sort" | |
"strings" | |
"github.com/PuerkitoBio/goquery" | |
) | |
// Char used to decode JSON request | |
type Char struct { | |
Word string | |
} | |
// XingCount holds Xing and its count | |
type XingCount struct { | |
Xing string | |
Count int | |
} | |
// XingList A list of XingCount used for sorting | |
type XingList []XingCount | |
func (p XingList) Len() int { return len(p) } | |
func (p XingList) Less(i, j int) bool { return p[i].Count < p[j].Count } | |
func (p XingList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } | |
func topWuxing(m map[string]int) string { | |
if len(m) == 0 { | |
return "" | |
} | |
xl := make(XingList, len(m)) | |
i := 0 | |
for k, v := range m { | |
xl[i] = XingCount{k, v} | |
i++ | |
} | |
sort.Sort(sort.Reverse(xl)) | |
ret := xl[0].Xing | |
for idx, v := range xl { | |
if idx > 0 && (xl[0].Count < v.Count*2) && v.Count > 1 { | |
ret = ret + v.Xing | |
} | |
} | |
return ret | |
} | |
// WuxingHandler accepts requests with json data {"char": "天"} and returns wuxing for the given character | |
func WuxingHandler(w http.ResponseWriter, r *http.Request) { | |
switch r.Method { | |
case "GET": | |
message := `Example POST data {word: 天}` | |
j, _ := json.Marshal(message) | |
w.Write(j) | |
case "POST": | |
var char Char | |
err := json.NewDecoder(r.Body).Decode(&char) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
res, _ := http.Get("http://www.zdic.net/hans/" + char.Word) | |
counts := make(map[string]int) | |
doc, _ := goquery.NewDocumentFromReader(res.Body) | |
wuxing := "金木水火土" | |
doc.Find(".definitions").Each(func(i int, s *goquery.Selection) { | |
def := s.Text() | |
for _, xing := range wuxing { | |
count := strings.Count(def, string(xing)) | |
counts[string(xing)] = count + counts[string(xing)] | |
} | |
}) | |
ret := topWuxing(counts) | |
j, _ := json.Marshal(ret) | |
w.Write(j) | |
default: | |
fmt.Fprintf(w, "Not Supported") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment