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.
go-library/service/movieapi/v2/app.go

85 lines
1.7 KiB

package v2
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"net/http"
"strconv"
"strings"
"time"
)
type App struct {
AppKey string
AppSecret string
Timeout time.Duration
}
type ErrResp struct {
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data"`
Code int `json:"code"`
}
func (app *App) request(url string, params map[string]interface{}) ([]byte, error) {
// common params
params["time"] = time.Now().Unix()
params["appKey"] = app.AppKey
// sign params
params["sign"] = app.getSign(app.AppSecret, params)
var req *http.Request
req, err := http.NewRequest("POST", fmt.Sprintf("https://movieapi2.pintoto.cn/%s", url), strings.NewReader(app.getRequestData(params)))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{}
httpClient.Timeout = app.Timeout
var response *http.Response
response, err = httpClient.Do(req)
if err != nil {
return nil, nil
}
// 请求错误
if response.StatusCode != 200 {
return nil, errors.New(fmt.Sprintf("请求错误:%d", response.StatusCode))
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
// 检查错误
apiErr := ErrResp{}
if err := json.Unmarshal(body, &apiErr); err != nil {
return nil, err
}
// 接口状态错误
if apiErr.Code != 200 {
return nil, errors.New(apiErr.Message)
}
return body, nil
}
func (app *App) GradeToFloat64(i interface{}) float64 {
switch v := i.(type) {
case string:
float, _ := strconv.ParseFloat(v, 64)
return float
case float64:
return v
case int64:
return float64(v) / math.Pow10(0)
default:
return 0
}
}