github.com/opcr-io/oras-go/v2@v2.0.0-20231122155130-eb4260d8a0ae/registry/remote/internal/errutil/errutil.go (about)

     1  /*
     2  Copyright The ORAS Authors.
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7  http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package errutil
    17  
    18  import (
    19  	"encoding/json"
    20  	"errors"
    21  	"io"
    22  	"net/http"
    23  
    24  	"github.com/opcr-io/oras-go/v2/registry/remote/errcode"
    25  )
    26  
    27  // maxErrorBytes specifies the default limit on how many response bytes are
    28  // allowed in the server's error response.
    29  // A typical error message is around 200 bytes. Hence, 8 KiB should be
    30  // sufficient.
    31  const maxErrorBytes int64 = 8 * 1024 // 8 KiB
    32  
    33  // ParseErrorResponse parses the error returned by the remote registry.
    34  func ParseErrorResponse(resp *http.Response) error {
    35  	resultErr := &errcode.ErrorResponse{
    36  		Method:     resp.Request.Method,
    37  		URL:        resp.Request.URL,
    38  		StatusCode: resp.StatusCode,
    39  	}
    40  	var body struct {
    41  		Errors errcode.Errors `json:"errors"`
    42  	}
    43  	lr := io.LimitReader(resp.Body, maxErrorBytes)
    44  	if err := json.NewDecoder(lr).Decode(&body); err == nil {
    45  		resultErr.Errors = body.Errors
    46  	}
    47  	return resultErr
    48  }
    49  
    50  // IsErrorCode returns true if err is an Error and its Code equals to code.
    51  func IsErrorCode(err error, code string) bool {
    52  	var ec errcode.Error
    53  	return errors.As(err, &ec) && ec.Code == code
    54  }