Пример #1
0
func suggestions(w rest.ResponseWriter, r *rest.Request) {
	var req data.SuggestionReq
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if req.FallbackLocale == "" {
		req.FallbackLocale = data.Locale("en")
	}
	if req.Locales == nil {
		rest.Error(w, "locales required", 400)
		return
	}
	if len(req.Query) > maxQueryLen {
		rest.Error(w, fmt.Sprintf("Max query length is %d", maxQueryLen), 400)
		return
	}

	resp, err := glosbe.Suggest(req)
	if err != nil {
		rest.Error((w), err.Error(), 500)
		return
	}

	w.WriteJson(resp)
}
Пример #2
0
// Suggest returns a slice of suggestions for a request.
// glosbe returns suggestions only for the source locale.
func Suggest(req data.SuggestionReq) (*[]data.Suggestion, error) {
	resp, err := req.FromCache()
	if err == nil {
		return resp, nil
	}

	source, err := gtranslate.Detect(req)
	if err != nil {
		return nil, err
	}

	source = req.NormalizeLocale(source)
	target := req.TargetLocale(source)

	query, err := makeSuggestQuery(req.Query, source, target)
	if err != nil {
		return nil, err
	}

	rawData, err := httputils.Get(query)
	if err != nil {
		return nil, err
	}

	resp, err = parseSuggestResp(rawData, source)
	if err != nil {
		return nil, err
	}

	if cacheErr := req.SaveCache(resp); cacheErr != nil {
		log.Println(cacheErr)
	}
	return resp, nil
}