github.com/goplus/yap@v0.8.1/ytest/util.go (about) 1 /* 2 * Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package ytest 18 19 import ( 20 "encoding/json" 21 "net/url" 22 "strconv" 23 24 "github.com/goplus/yap/test" 25 "github.com/goplus/yap/ytest/auth" 26 "github.com/goplus/yap/ytest/auth/bearer" 27 ) 28 29 // ----------------------------------------------------------------------------- 30 31 // Bearer creates a Bearer Authorization by specified token. 32 func Bearer(token string) auth.RTComposer { 33 return bearer.New(token) 34 } 35 36 // ----------------------------------------------------------------------------- 37 38 // JsonEncode encodes a value into string in json format. 39 func JsonEncode(v any) string { 40 b, err := json.Marshal(v) 41 if err != nil { 42 test.Fatal("json.Marshal failed:", err) 43 } 44 return string(b) 45 } 46 47 // Form encodes a map value into string in form format. 48 func Form(m map[string]any) (ret url.Values) { 49 ret = make(url.Values) 50 for k, v := range m { 51 ret[k] = formVal(v) 52 } 53 return ret 54 } 55 56 func formVal(val any) []string { 57 switch v := val.(type) { 58 case string: 59 return []string{v} 60 case []string: 61 return v 62 case int: 63 return []string{strconv.Itoa(v)} 64 case bool: 65 if v { 66 return []string{"true"} 67 } 68 return []string{"false"} 69 case float64: 70 return []string{strconv.FormatFloat(v, 'g', -1, 64)} 71 } 72 test.Fatalf("formVal unexpected type: %T\n", val) 73 return nil 74 } 75 76 // -----------------------------------------------------------------------------