pixiv-scrapper/gelbooru/api.go

82 lines
1.6 KiB
Go

package gelbooru
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type API struct {
apiKey string
userID string
httpClient http.Client
}
const (
apiEndpoint = "https://gelbooru.com/index.php"
)
func newRequest(params map[string]string) (r *http.Request, err error) {
if _, ok := params["page"]; !ok {
params["page"] = "dapi"
}
if _, ok := params["s"]; !ok {
params["s"] = "post"
}
if _, ok := params["q"]; !ok {
params["s"] = "index"
}
if _, ok := params["json"]; !ok {
params["json"] = "1"
}
var addr string
for name, value := range params {
if len(addr) == 0 {
addr = fmt.Sprintf("%s?%s=%s", addr, name, value)
} else {
addr = fmt.Sprintf("%s&%s=%s", addr, name, value)
}
}
addr = fmt.Sprintf("%s%s", apiEndpoint, addr)
r, err = http.NewRequest(http.MethodGet, addr, nil)
if err != nil {
err = fmt.Errorf("newRequest: %s", err.Error())
}
return
}
func New(userID string, APIKey string) (a API) {
a.userID = userID
a.apiKey = APIKey
a.httpClient = http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: nil,
Timeout: time.Second * 30,
}
return
}
func (a *API) Search(querry string) (p []Post, err error) {
req, err := newRequest(map[string]string{"tags": querry})
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
return
}
resp, err := a.httpClient.Do(req)
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &p)
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
}
return
}