github.com/erda-project/erda-infra@v1.0.9/providers/component-protocol/utils/cputil/urlquery.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     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  package cputil
    16  
    17  import (
    18  	"encoding/base64"
    19  	"fmt"
    20  
    21  	"github.com/erda-project/erda-infra/pkg/strutil"
    22  	"github.com/erda-project/erda-infra/providers/component-protocol/cptype"
    23  )
    24  
    25  const (
    26  	compURLQuerySuffix = "__urlQuery"
    27  )
    28  
    29  // MakeCompURLQueryKey make url query key for component.
    30  func MakeCompURLQueryKey(compName string) string { return compName + compURLQuerySuffix }
    31  
    32  // SetURLQuery set data to url query.
    33  func SetURLQuery(sdk *cptype.SDK, data interface{}) {
    34  	b, err := json.Marshal(data)
    35  	if err != nil {
    36  		panic(fmt.Errorf("failed to set url query, err: %v", err))
    37  	}
    38  	urlQueryStr := base64.URLEncoding.EncodeToString(b)
    39  	// set into comp options
    40  	if sdk.Comp.Options == nil {
    41  		sdk.Comp.Options = &cptype.ComponentOptions{}
    42  	}
    43  	sdk.Comp.Options.URLQuery = urlQueryStr
    44  }
    45  
    46  // GetURLQuery get component's url query and parse to `resultStructPtr`.
    47  func GetURLQuery(sdk *cptype.SDK, resultStructPtr interface{}) error {
    48  	if sdk.InParams == nil {
    49  		return nil
    50  	}
    51  	if resultStructPtr == nil {
    52  		return fmt.Errorf("result receiver pointer can't be nil")
    53  	}
    54  	encodedURLQuery := strutil.String(sdk.InParams[MakeCompURLQueryKey(sdk.Comp.Name)])
    55  	jsonEncodedURLQuery, err := base64.URLEncoding.DecodeString(encodedURLQuery)
    56  	if err != nil {
    57  		return fmt.Errorf("failed to get url query from inParams, err: %v", err)
    58  	}
    59  	err = json.Unmarshal(jsonEncodedURLQuery, resultStructPtr)
    60  	if err != nil {
    61  		return fmt.Errorf("failed to json unmarshal json encoded url query, err: %v", err)
    62  	}
    63  	return nil
    64  }
    65  
    66  // MustGetURLQuery must GetURLQuery.
    67  func MustGetURLQuery(sdk *cptype.SDK, resultStructPtr interface{}) {
    68  	err := GetURLQuery(sdk, resultStructPtr)
    69  	if err != nil {
    70  		panic(err)
    71  	}
    72  }