diff options
| author | Shulhan <m.shulhan@gmail.com> | 2020-03-31 01:11:26 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2020-04-01 06:28:03 +0700 |
| commit | 8a141995aabdee289d2b096bd77a10b52b08a1bf (patch) | |
| tree | 98af569d4c3e2620809ce591c2733184cd77db8f /api_client.go | |
| parent | 84fdfdb6ae4175a125fc67a6aed377476d31ee0e (diff) | |
| download | kamusku-8a141995aabdee289d2b096bd77a10b52b08a1bf.tar.xz | |
all: implement server and client for dictionary API
Currently the server and client can onyl handle API for looking up
definitions of the words through "/api/definisi" URL.
Diffstat (limited to 'api_client.go')
| -rw-r--r-- | api_client.go | 92 |
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 +} |
