Skip to content

Commit

Permalink
implement GetUserItems
Browse files Browse the repository at this point in the history
  • Loading branch information
maiyama18 committed Apr 1, 2019
1 parent a4aa10f commit f5dd926
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion miniqiita.go
Expand Up @@ -2,10 +2,16 @@ package miniqiita

import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"strconv"
)

type Client struct {
Expand Down Expand Up @@ -40,5 +46,52 @@ type Item struct {
}

func (c *Client) GetUserItems(ctx context.Context, userID string, page, perPage int) ([]*Item, error) {
return nil, nil
reqURL := *c.BaseURL

// set path
reqURL.Path = path.Join(reqURL.Path, "users", userID, "items")

// set query
q := reqURL.Query()
q.Add("page", strconv.Itoa(page))
q.Add("per_page", strconv.Itoa(perPage))
reqURL.RawQuery = q.Encode()

// instantiate request
req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil)
if err != nil {
return nil, err
}

// set header
req.Header.Set("User-Agent", "qiita-go-client")

// set context
req = req.WithContext(ctx)

// send request
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

switch resp.StatusCode {
case http.StatusOK:
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var items []*Item
if err := json.Unmarshal(bodyBytes, &items); err != nil {
return nil, err
}
return items, nil
case http.StatusBadRequest:
return nil, errors.New("bad request. some parameters may be invalid")
case http.StatusNotFound:
return nil, fmt.Errorf("not found. user with id '%s' may not exist", userID)
default:
return nil, errors.New("unexpected error")
}
}

0 comments on commit f5dd926

Please sign in to comment.