Skip to content

Commit

Permalink
增加错误处理
Browse files Browse the repository at this point in the history
  • Loading branch information
tsosunchia committed Oct 8, 2023
1 parent ef141bd commit 5f1a516
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
20 changes: 15 additions & 5 deletions pow_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ func RetToken(getTokenParams *GetTokenParams) (string, error) {
}
}
if getTokenParams.Proxy != nil {
if client.Transport == nil {
client.Transport = &http.Transport{}
}
client.Transport.(*http.Transport).Proxy = http.ProxyURL(getTokenParams.Proxy)
}
challengeParams := &ChallengeParams{
Expand Down Expand Up @@ -116,11 +119,7 @@ func requestChallenge(challengeParams *ChallengeParams) (*RequestResponse, error
//req.Header.Add("Host", getTokenParams.Host)
req.Host = challengeParams.Host
resp, err := challengeParams.Client.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
// 如果http_code为429
if resp.StatusCode == http.StatusTooManyRequests {
log.Fatalln("请求次数超限,请稍后再试")
}
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
Expand All @@ -129,6 +128,14 @@ func requestChallenge(challengeParams *ChallengeParams) (*RequestResponse, error
fmt.Println(err)
}
}(resp.Body)

if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusTooManyRequests {
log.Fatalln("请求次数超限,请稍后再试")
}
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}

var challengeResponse RequestResponse
err = json.NewDecoder(resp.Body).Decode(&challengeResponse)
if err != nil {
Expand Down Expand Up @@ -184,6 +191,9 @@ func submitAnswer(challengeParams *ChallengeParams, challengeResponse *RequestRe
}(resp.Body)

if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusTooManyRequests {
return "", errors.New("请求次数超限")
}
bodyBytes, _ := io.ReadAll(resp.Body)
return "", errors.New(string(bodyBytes))
}
Expand Down
2 changes: 1 addition & 1 deletion pow_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func TestGetToken(t *testing.T) {
token, err := getToken("103.120.18.35", "api.leo.moe", "443")
token, err := getToken("api.leo.moe", "api.leo.moe", "443")
fmt.Println(token, err)
assert.NoError(t, err, "GetToken() returned an error")
}
Expand Down

0 comments on commit 5f1a516

Please sign in to comment.