github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/config/client/client.go (about)

     1  package client
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  
     7  	proto "github.com/tickoalcantara12/micro/v3/proto/config"
     8  	"github.com/tickoalcantara12/micro/v3/service/client"
     9  	"github.com/tickoalcantara12/micro/v3/service/config"
    10  	"github.com/tickoalcantara12/micro/v3/service/context"
    11  	"github.com/tickoalcantara12/micro/v3/service/errors"
    12  )
    13  
    14  var (
    15  	defaultNamespace = "micro"
    16  	name             = "config"
    17  )
    18  
    19  type srv struct {
    20  	opts      config.Options
    21  	namespace string
    22  	client    proto.ConfigService
    23  }
    24  
    25  func (m *srv) Get(path string, options ...config.Option) (config.Value, error) {
    26  	o := config.Options{}
    27  	for _, option := range options {
    28  		option(&o)
    29  	}
    30  	nullValue := config.NewJSONValue([]byte("null"))
    31  	req, err := m.client.Get(context.DefaultContext, &proto.GetRequest{
    32  		Namespace: m.namespace,
    33  		Path:      path,
    34  		Options: &proto.Options{
    35  			Secret: o.Secret,
    36  		},
    37  	}, client.WithAuthToken())
    38  	if verr := errors.FromError(err); verr != nil && verr.Code == http.StatusNotFound {
    39  		return nullValue, nil
    40  	} else if err != nil {
    41  		return nullValue, err
    42  	}
    43  
    44  	return config.NewJSONValue([]byte(req.Value.Data)), nil
    45  }
    46  
    47  func (m *srv) Set(path string, value interface{}, options ...config.Option) error {
    48  	o := config.Options{}
    49  	for _, option := range options {
    50  		option(&o)
    51  	}
    52  	dat, _ := json.Marshal(value)
    53  	_, err := m.client.Set(context.DefaultContext, &proto.SetRequest{
    54  		Namespace: m.namespace,
    55  		Path:      path,
    56  		Value: &proto.Value{
    57  			Data: string(dat),
    58  		},
    59  		Options: &proto.Options{
    60  			Secret: o.Secret,
    61  		},
    62  	}, client.WithAuthToken())
    63  	return err
    64  }
    65  
    66  func (m *srv) Delete(path string, options ...config.Option) error {
    67  	_, err := m.client.Delete(context.DefaultContext, &proto.DeleteRequest{
    68  		Namespace: m.namespace,
    69  		Path:      path,
    70  	}, client.WithAuthToken())
    71  	return err
    72  }
    73  
    74  func (m *srv) String() string {
    75  	return "service"
    76  }
    77  
    78  func NewConfig(namespace string) *srv {
    79  	addr := name
    80  	if len(namespace) == 0 {
    81  		namespace = defaultNamespace
    82  	}
    83  
    84  	s := &srv{
    85  		namespace: namespace,
    86  		client:    proto.NewConfigService(addr, client.DefaultClient),
    87  	}
    88  
    89  	return s
    90  }