目录

文件上传

可以通过context包来对请求进行超时限制

// Upload upload bfs.
func (d *Dao) Upload(c context.Context, fileType string, body io.Reader) (location string, err error) {
    req, err := http.NewRequest(_method, _url, body)
    if err != nil {
        log.Error("http.NewRequest error (%v) | fileType(%s) body(%v)", err, fileType, body)
        return
    }
    expire := time.Now().Unix()
    authorization := authorize(_key, _secret, _method, _bucket, expire)
    req.Header.Set("Host", _url)
    req.Header.Add("Date", fmt.Sprint(expire))
    req.Header.Add("Authorization", authorization)
    req.Header.Add("Content-Type", fileType)
    // timeout
    c, cancel := context.WithTimeout(c, time.Duration(d.c.Bfs.Timeout))
    req = req.WithContext(c)
    defer cancel()

    resp, err := d.client.Do(req)
    if err != nil {
        log.Error("d.Client.Do error(%v) | _url(%s) req(%v)", err, _url, req)
        err = ecode.BfsUploadServiceUnavailable
        return
    }
    if resp.StatusCode != http.StatusOK {
        log.Error("Upload http.StatusCode nq http.StatusOK (%d) | url(%s)", resp.StatusCode, _url)
        err = ecode.BfsUploadStatusErr
        return
    }
    header := resp.Header
    code := header.Get("Code")
    if code != strconv.Itoa(http.StatusOK) {
        log.Error("strconv.Itoa err, code(%s) | url(%s)", code, _url)
        err = ecode.BfsUploadCodeErr
        return
    }
    location = header.Get("Location")
    return
}

请求参数
func (d *Dao) Validate(c context.Context, challenge, seccode, clientType, captchaID string, mid int64) (res *geetest.ValidateRes, err error) {
    params := url.Values{}
    params.Set("seccode", seccode)
    params.Set("challenge", challenge)
    params.Set("captchaid", captchaID)
    params.Set("client_type", clientType)
    params.Set("ip_address", metadata.String(c, metadata.RemoteIP))
    params.Set("json_format", "1")
    params.Set("sdk", "golang_3.0.0")
    params.Set("user_id", strconv.FormatInt(mid, 10))
    params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
    req, err := http.NewRequest("POST", d.validateURI, strings.NewReader(params.Encode()))
    if err != nil {
        log.Error("http.NewRequest error(%v) | uri(%s) params(%s)", err, d.validateURI, params.Encode())
        err = ecode.CreativeGeetestAPIErr
        return
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    if err = d.clientX.Do(c, req, &res); err != nil {
        log.Error("d.client.Do error(%v)", err)
        err = ecode.CreativeGeetestAPIErr
        return
    }
    return
}