使sqlx MapScan返回字符串

The sqlx package has a MapScan function that's quite handy in that it returns a row as a map (map[string]interface{}) but all string columns come out as runes (if I'm not mistaken). Is there a way to have it just return as strings instead?

sqlx - github.com/jmoiron/sqlx

I have encountered a similar issue when dealing with sql in go. Some googling lead me to the go driver docs. Here is what they have for a Value type returned from a query.

Value is a value that drivers must be able to handle. It is either nil or an instance of one of these types:

  • int64
  • float64
  • bool
  • []byte
  • string [*] everywhere except from Rows.Next.
  • time.Time

Strings are returned as byte slices (when you attempt to encode []bytes into json it base64s it). I have not found a way within the framework of sqlx or sql/db to return strings instead of []byte slices, but did come up with a quick and dirty conversion for slices in a map. There is limited type checking, but it is a good start.

func convertStrings(in map[string]interface{}) {
    for k, v := range in {
        t := reflect.TypeOf(v)
        if t != nil {
            switch t.Kind() {
            case reflect.Slice:
                in[k] = fmt.Sprintf("%s", v)

            default:
                // do nothing
            }
        }
    }
}