summaryrefslogtreecommitdiff
path: root/api_client.go
diff options
context:
space:
mode:
Diffstat (limited to 'api_client.go')
-rw-r--r--api_client.go92
1 files changed, 92 insertions, 0 deletions
diff --git a/api_client.go b/api_client.go
new file mode 100644
index 0000000..eb1c2f7
--- /dev/null
+++ b/api_client.go
@@ -0,0 +1,92 @@
+// Copyright 2020, Shulhan <m.shulhan@gmail.com>. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package kbbi
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+//
+// apiClient is client that connect to cached server API.
+//
+type apiClient struct {
+ url string
+ conn *http.Client
+}
+
+//
+// newAPIClient create a new client for server API.
+// If url is empty it will use default server API.
+//
+func newAPIClient(url string) (client *apiClient) {
+ if len(url) == 0 {
+ url = defServerAPI
+ }
+
+ client = &apiClient{
+ url: url,
+ conn: &http.Client{
+ Timeout: defTimeout,
+ },
+ }
+
+ return client
+}
+
+//
+// Lookup the definition of words through server API.
+//
+func (client *apiClient) CariDefinisi(words []string) (
+ res DefinisiResponse, err error,
+) {
+ if len(words) == 0 {
+ return nil, nil
+ }
+
+ params := url.Values{}
+ params.Set(paramNameKata, strings.Join(words, ","))
+
+ req, err := http.NewRequest(http.MethodGet, client.url+pathAPIDefinisi, nil)
+ if err != nil {
+ return nil, fmt.Errorf("CariDefinisi: %w", err)
+ }
+
+ req.URL.RawQuery = params.Encode()
+
+ httpRes, err := client.conn.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("CariDefinisi: %w", err)
+ }
+
+ resBody, err := ioutil.ReadAll(httpRes.Body)
+ if err != nil {
+ return nil, fmt.Errorf("CariDefinisi: %w", err)
+ }
+
+ defer httpRes.Body.Close()
+
+ if len(resBody) == 0 {
+ return res, nil
+ }
+
+ err = res.unpack(resBody)
+ if err != nil {
+ return nil, fmt.Errorf("CariDefinisi: %w", err)
+ }
+
+ return res, nil
+}
+
+//
+// ListKataDasar list all of the root words in dictionary.
+//
+func (client *apiClient) ListKataDasar() (res DaftarKata, err error) {
+ //TODO: return cached list.
+ return res, nil
+}