/* * Hexacode Types * Package: gitlab.hexacode.org/go-libs/hctypes * Maintainer: Azzis Arswendo * * Copyright (C) 2023 Hexacode Teknologi Indonesia * All Rights Reserved */ package hctypes import ( "fmt" "net/url" "strconv" ) func stringify_parameters(name string, parameters interface{}) Dict { ret := NewDict() for key, value := range flatten_parameters(parameters) { ret[fmt.Sprintf("%s%s", name, key)] = value } return ret } func flatten_parameters(parameters Item) Dict { ret := NewDict() flatten(parameters, "", ret) return ret } func flatten(item Item, prefix string, ret Dict) { switch val := item.(type) { case Dict: for key, value := range val { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } case map[string]Item: for key, value := range val { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } case map[string]interface{}: for key, value := range val { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } case List: parameters_list := NewDict() for i, v := range val { parameters_list[strconv.Itoa(i)] = v } for key, value := range parameters_list { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } case []Item: parameters_list := NewDict() for i, v := range val { parameters_list[strconv.Itoa(i)] = v } for key, value := range parameters_list { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } case []interface{}: parameters_list := NewDict() for i, v := range val { parameters_list[strconv.Itoa(i)] = v } for key, value := range parameters_list { flatten(value, fmt.Sprintf("%s[%s]", prefix, key), ret) } default: ret[prefix] = val } } // ToQueryString converts the Dict to a URL query string. // // Example: // // dict := hctypes.Dict{ // "key1": "value1", // "key2": 42, // } // // dict.ToQueryString().Encode() // // output: "key1=value1&key2=42" // // No parameters. // Returns url.Values. func (this Dict) ToQueryString() url.Values { values := make(url.Values) copy := this.Copy() for key, value := range copy { stringified := stringify_parameters(key, value) for key1, value1 := range stringified { r := fmt.Sprintf("%v", value1) if r == "" { r = "" } values.Add(key1, r) } } return values }