github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/transports/standard/header.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package standard
    19  
    20  import (
    21  	"github.com/aacfactory/fns/commons/bytex"
    22  	"github.com/aacfactory/fns/transports"
    23  	"net/http"
    24  	"net/textproto"
    25  )
    26  
    27  func NewHeader() transports.Header {
    28  	return make(httpHeader)
    29  }
    30  
    31  func WrapHttpHeader(h http.Header) transports.Header {
    32  	return httpHeader(h)
    33  }
    34  
    35  type httpHeader map[string][]string
    36  
    37  func (h httpHeader) Add(key []byte, value []byte) {
    38  	textproto.MIMEHeader(h).Add(bytex.ToString(key), bytex.ToString(value))
    39  }
    40  
    41  func (h httpHeader) Set(key []byte, value []byte) {
    42  	textproto.MIMEHeader(h).Set(bytex.ToString(key), bytex.ToString(value))
    43  }
    44  
    45  func (h httpHeader) Get(key []byte) []byte {
    46  	return bytex.FromString(textproto.MIMEHeader(h).Get(bytex.ToString(key)))
    47  }
    48  
    49  func (h httpHeader) Del(key []byte) {
    50  	textproto.MIMEHeader(h).Del(bytex.ToString(key))
    51  }
    52  
    53  func (h httpHeader) Values(key []byte) [][]byte {
    54  	vv := textproto.MIMEHeader(h).Values(bytex.ToString(key))
    55  	if len(vv) == 0 {
    56  		return nil
    57  	}
    58  	values := make([][]byte, 0, 1)
    59  	for _, v := range vv {
    60  		values = append(values, bytex.FromString(v))
    61  	}
    62  	return values
    63  }
    64  
    65  func (h httpHeader) Len() int {
    66  	return len(h)
    67  }
    68  
    69  func (h httpHeader) Foreach(fn func(key []byte, values [][]byte)) {
    70  	if fn == nil {
    71  		return
    72  	}
    73  	for key, values := range h {
    74  		vv := make([][]byte, 0, 1)
    75  		for _, value := range values {
    76  			vv = append(vv, bytex.FromString(value))
    77  		}
    78  		fn(bytex.FromString(key), vv)
    79  	}
    80  }
    81  
    82  func (h httpHeader) Reset() {
    83  	clear(h)
    84  }