github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/http/helper_debug_env.go (about)

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/base/consts"
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
    10  	"github.com/machinefi/w3bstream/pkg/depends/kit/kit"
    11  )
    12  
    13  var (
    14  	EnvQueryRouter = kit.NewRouter(&EnvQuery{})
    15  	EnvSetRouter   = kit.NewRouter(&EnvSet{})
    16  )
    17  
    18  func RegisterEnvRouters(r *kit.Router) {
    19  	r.Register(EnvQueryRouter)
    20  	r.Register(EnvSetRouter)
    21  }
    22  
    23  type EnvQuery struct {
    24  	httpx.MethodGet
    25  	K string `in:"query" name:"k,omitempty"`
    26  }
    27  
    28  func (r *EnvQuery) Path() string { return "/env" }
    29  
    30  func (r *EnvQuery) Output(ctx context.Context) (interface{}, error) {
    31  	if r.K != "" {
    32  		return map[string]string{
    33  			r.K: os.Getenv(r.K),
    34  		}, nil
    35  	}
    36  	vars := os.Environ()
    37  	m := make(map[string]string)
    38  	prefix := ""
    39  	if os.Getenv(consts.EnvProjectName) != "" {
    40  		prefix = os.Getenv(consts.EnvProjectName)
    41  		prefix = strings.ToUpper(strings.Replace(prefix, "-", "_", -1))
    42  	}
    43  
    44  	for _, v := range vars {
    45  		pair := strings.SplitN(v, "=", 2)
    46  		if len(pair) != 2 {
    47  			continue
    48  		}
    49  		key, val := pair[0], pair[1]
    50  		if prefix != "" && strings.HasPrefix(key, prefix) {
    51  			m[key] = val
    52  		}
    53  	}
    54  	return m, nil
    55  }
    56  
    57  type EnvSet struct {
    58  	httpx.MethodPost
    59  	K string `in:"query"           name:"key"`
    60  	V string `in:"query,omitempty" name:"key"`
    61  }
    62  
    63  func (r *EnvSet) Path() string { return "/env" }
    64  
    65  func (r *EnvSet) Output(ctx context.Context) (interface{}, error) {
    66  	return nil, os.Setenv(r.K, r.V)
    67  }