douyaosi3164 2018-07-29 15:17
浏览 565
已采纳

在go开发中过度使用map [string] interface {}?

The majority of my development experience has been from dynamically typed languages like PHP and Javascript. I've been practicing with Golang for about a month now by re-creating some of my old PHP/Javascript REST APIs in Golang. I feel like I'm not doing things the Golang way most of the time. Or more generally, I'm not use to working with strongly typed languages. I feel like I'm making excessive use of map[string]interface{} and slices of them to box up data as it comes in from http requests or when it gets shipped out as json http output. So what I'd like to know is if what I'm about to describe goes against the philosophy of golang development? Or if I'm breaking the principles of developing with strongly typed languages?

Right now, about 90% of the program flow for REST Apis I've rewritten with Golang can be described by these 5 steps.

STEP 1 - Receive Data

I receive http form data from http.Request.ParseForm() as formvals := map[string][]string. Sometimes I will store serialized JSON objects that need to be unmarshaled like jsonUserInfo := json.Unmarshal(formvals["user_information"][0]) /* gives some complex json object */.

STEP 2 - Validate Data

I do validation on formvals to make sure all the data values are what I expect before using it in SQL queries. I treat everyting as a string, then use Regex to determine if the string format and business logic is valid (eg. IsEmail, IsNumeric, IsFloat, IsCASLCompliant, IsEligibleForVoting,IsLibraryCardExpired etc...). I've written my own Regex and custom functions for these types of validations

STEP 3 - Bind Data to SQL Queries

I use golang's database/sql.DB to take my formvals and bind them to my Query and Exec functions like this Query("SELECT * FROM tblUser WHERE user_id = ?, user_birthday > ? ",formvals["user_id"][0], jsonUserInfo["birthday"]). I never care about the data types I'm supplying as arguments to be bound, so they're all probably strings. I trust the validation in the step immediately above has determined they are acceptable for SQL use.

STEP 4 - Bind SQL results to []map[string]interface{}{}

I Scan() the results of my queries into a sqlResult := []map[string]interface{}{} because I don't care if the value types are null, strings, float, ints or whatever. So the schema of an sqlResult might look like:

sqlResult =>
    [0] {
        "user_id":"1"
        "user_name":"Bob Smith"
        "age":"45"
        "weight":"34.22"
    },
    [1] {
        "user_id":"2"
        "user_name":"Jane Do"
        "age":nil
        "weight":"22.22"
    }

I wrote my own eager load function so that I can bind more information like so EagerLoad("tblAddress", "JOIN ON tblAddress.user_id",&sqlResult) which then populates sqlResult with more information of the type []map[string]interface{}{} such that it looks like this:

sqlResult =>
    [0] {
        "user_id":"1"
        "user_name":"Bob Smith"
        "age":"45"
        "weight":"34.22"
        "addresses"=>
            [0] {
                "type":"home"
                "address1":"56 Front Street West"
                "postal":"L3L3L3"
                "lat":"34.3422242"
                "lng":"34.5523422"
            }
            [1] {
                "type":"work"
                "address1":"5 Kennedy Avenue"
                "postal":"L3L3L3"
                "lat":"34.3422242"
                "lng":"34.5523422"
            }
    },
    [1] {
        "user_id":"2"
        "user_name":"Jane Do"
        "age":nil
        "weight":"22.22"
        "addresses"=>
            [0] {
                "type":"home"
                "address1":"56 Front Street West"
                "postal":"L3L3L3"
                "lat":"34.3422242"
                "lng":"34.5523422"
            }
    }

STEP 5 - JSON Marshal and send HTTP Response

then I do a http.ResponseWriter.Write(json.Marshal(sqlResult)) and output data for my REST API

Recently, I've been revisiting articles with code samples that use structs in places I would have used map[string]interface{}. For example, I wanted to refactor Step 2 with a more standard approach that other golang developers would use. So I found this https://godoc.org/gopkg.in/go-playground/validator.v9, except all it's examples are with structs . I also noticed that most blogs that talk about database/sql scan their SQL results into typed variables or structs with typed properties, as opposed to my Step 4 which just puts everything into map[string]interface{}

Hence, i started writing this question. I feel the map[string]interface{} is so useful because majority of the time,I don't really care what the data is and it gives me to the freedom in Step 4 to construct any data schema on the fly before I dump it as JSON http response. I do all this with as little code verbosity as possible. But this means my code is not as ready to leverage Go's validation tools, and it doesn't seem to comply with the golang community's way of doing things.

So my question is, what do other golang developers do with regards to Step 2 and Step 4? Especially in Step 4...do Golang developers really encourage specifying the schema of the data through structs and strongly typed properties? Do they also specify structs with strongly typed properties along with every eager loading call they make? Doesn't that seem like so much more code verbosity?

  • 写回答

1条回答 默认 最新

  • ds08541 2018-07-29 16:08
    关注

    It really depends on the requirements just like you have said you don't require to process the json it comes from the request or from the sql results. Then you can easily unmarshal into interface{}. And marshal the json coming from sql results.

    For Step 2

    Golang has library which works on validation of structs used to unmarshal json with tags for the fields inside.

    https://github.com/go-playground/validator

    type Test struct {
        Field `validate:"max=10,min=1"`
    }
    
    // max will be checked then min
    

    you can also go to godoc for validation library. It is very good implementation of validation for json values using struct tags.

    For STEP 4

    Most of the times, We use structs if we know the format and data of our JSON. Because it provides us more control over the data types and other functionality. For example if you wants to empty a JSON feild if you don't require it in your JSON. You should use struct with _ json tag.

    Now you have said that you don't care if the result coming from sql is empty or not. But if you do it again comes to using struct. You can scan the result into struct with sql.NullTypes. With that also you can provide json tag for omitempty if you wants to omit the json object when marshaling the data when sending a response.

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

    The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

    The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

    As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

    Example of json tags

    // Field appears in JSON as key "myName".
    Field int `json:"myName"`
    
    // Field appears in JSON as key "myName" and
    // the field is omitted from the object if its value is empty,
    // as defined above.
    Field int `json:"myName,omitempty"`
    
    // Field appears in JSON as key "Field" (the default), but
    // the field is skipped if empty.
    // Note the leading comma.
    Field int `json:",omitempty"`
    
    // Field is ignored by this package.
    Field int `json:"-"`
    
    // Field appears in JSON as key "-".
    Field int `json:"-,"`
    

    As you can analyze from above information given in Golang spec for json marshal. Struct provide so much control over json. That's why Golang developer most probably use structs.

    Now on using map[string]interface{} you should use it when you don't the structure of your json coming from the server or the types of fields. Most Golang developers stick to structs wherever they can.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。