github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/metax/meta.go (about)

     1  package metax
     2  
     3  import (
     4  	"context"
     5  	"net/url"
     6  	"strings"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/x/contextx"
     9  )
    10  
    11  type key struct{}
    12  
    13  func ContextWith(ctx context.Context, key string, values ...string) context.Context {
    14  	return ContextWithMeta(ctx, Meta{key: values})
    15  }
    16  
    17  func ContextWithMeta(ctx context.Context, meta Meta) context.Context {
    18  	return contextx.WithValue(ctx, key{}, GetMetaFrom(ctx).Merge(meta))
    19  }
    20  
    21  func GetMetaFrom(ctx context.Context) Meta {
    22  	if m, ok := ctx.Value(key{}).(Meta); ok {
    23  		return m
    24  	}
    25  	return Meta{}
    26  }
    27  
    28  func ParseMeta(query string) Meta {
    29  	if !strings.Contains(query, "=") {
    30  		return Meta{
    31  			"_id": []string{query},
    32  		}
    33  	}
    34  	values, err := url.ParseQuery(query)
    35  	if err == nil {
    36  		return Meta(values)
    37  	}
    38  	return Meta{}
    39  }
    40  
    41  type Meta map[string][]string
    42  
    43  func (m Meta) Merge(metas ...Meta) Meta {
    44  	meta := m.Clone()
    45  
    46  	for _, me := range metas {
    47  		for k, values := range me {
    48  			if k == "" {
    49  				continue
    50  			}
    51  			if k[0] == '_' {
    52  				meta[k] = values
    53  				continue
    54  			}
    55  			meta.Add(k, values...)
    56  		}
    57  	}
    58  
    59  	return meta
    60  }
    61  
    62  func (m Meta) Clone() Meta {
    63  	meta := Meta{}
    64  	for k, v := range m {
    65  		meta[k] = v
    66  	}
    67  	return meta
    68  }
    69  
    70  func (m Meta) Add(key string, values ...string) {
    71  	m[key] = append(m[key], values...)
    72  }
    73  
    74  func (m Meta) Get(key string) string {
    75  	if m == nil {
    76  		return ""
    77  	}
    78  	vs := m[key]
    79  	if len(vs) == 0 {
    80  		return ""
    81  	}
    82  	return vs[0]
    83  }
    84  
    85  func (m Meta) With(key string, values ...string) Meta {
    86  	meta := m.Clone()
    87  	meta[key] = values
    88  	return meta
    89  }
    90  
    91  func (m Meta) String() string {
    92  	return url.Values(m).Encode()
    93  }