**WORK IN PROGRESS** golang API client for interacting with the jschan imageboard API.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

65 lines
1.3 KiB

package jschan
import (
"net/http"
"time"
"fmt"
"encoding/json"
"errors"
)
type Client struct {
BaseURL string
SessionCookie string
CsrfToken string
HTTPClient *http.Client
}
func NewClient(baseURL string) *Client {
return &Client{
BaseURL: baseURL,
SessionCookie: "",
CsrfToken: "",
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}
type DynamicResponse struct {
Title string `json:"title"`
Message string `json:"message"`
Redirect string `json:"redirect,omitempty"`
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
req.Header.Set("Accept", "application/json; charset=utf-8")
//req.Header.Set("Content-Type", "application/json; charset=utf-8")
if c.SessionCookie != "" {
req.Header.Set("Cookie", fmt.Sprintf("connect.sid=%s", c.SessionCookie))
}
if c.CsrfToken != "" {
// TODO
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes DynamicResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
fullResponse := v
if err = json.NewDecoder(res.Body).Decode(&fullResponse); err != nil {
return err
}
return nil
}