dsa45664 2019-01-09 03:53
浏览 61
已采纳

创建具有类型接口的地图以通过URL参数接受任意数据类型

I want to convert URL parameters from a string, to the correct data type and store it in a map. I believe the type should be []interface, to store a list of multiple data types.

I am creating a key-value store, but at the moment, it only stores strings. I have read up on GOB to convert the data into bytes, but don't understand it.

I have tried type assertion, however, I don't believe in my case this will work as the data is coming from the URL which by default is already a string. How do I detect whether the entry is a string, int, boolean etc?

Map:

var data map[string][]string 

handleFunc in the main func which calls the handleCreate func

r.HandleFunc("/insert/{key}/{value}", handleCreate).Methods("POST")  

handleFunc function

func handleCreate(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)

k := params["key"]
v := params["value"]

data[k] = append(data[k], v)
fmt.Fprintf(w, "KEY: %v: VALUE: %v was inserted into the key-value store successfully", k, v)
}

A link to the full code:

https://github.com/RipRoss/TrainingProjects/blob/master/main.go

The expected result is to store the value given in the URL as what it is intended for. For example /dog/Zeus would store Zeus as a string with key 'dog' and /cash/1000 would store 1000 as type int with key 'cash'

  • 写回答

2条回答 默认 最新

  • doujie4050 2019-01-09 05:26
    关注

    I have tried type assertion, however, I don't believe in my case this will work as the data is coming from the URL which by default is already a string. How do I detect whether the entry is a string, int, boolean etc?

    In general it's not a very good idea to make things overly dynamic (makes reasoning about things more complicated than it needs to be). Better to define a struct and then read values into it.

    That said, if we stick to the wording of your question, there are things you can do:

    For example, create a generic type that can store multiple versions of a value, along with a flag to indicate whether it correctly parsed into that type:

    type GenericValue struct {
        String string
    
        Integer int
        IntegerOK bool
    
        Float float64
        FloatOK bool
    
        Boolean bool
        BooleanOK bool
    }
    
    func ParseGenericValue(v string) GenericValue {
        var result GenericValue
        var err error
        result.String = v
        result.Integer, err = strconv.Atoi(v)
        result.IntegerOK = err == nil
        result.Float, err = strconv.ParseFloat(v, 64)
        result.FloatOK = err == nil
        result.Boolean, err = strconv.ParseBool(v)
        result.BooleanOK = err == nil
        return result
    }
    

    All this does is use the strconv package to try to parse the input string as an integer/float/boolean and if the parse is successful it makrs the corresponding OK field. For example, if IntegerOK is true then this indicates that parsing this string into an integer was successful.

    The GenericValue struct still holds the original input string, so you can use it to check if this value is an integer and do something with it, or check if it's a string and do something else

    var v = ParseGenericValue("2")
    
    if v.IntegerOK {
        // do something with v.Integer
    } else {
        // maybe just handle v.String in a different way
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)