Problem when creating WebService in Golang

2

I am doing a WS , where I make a query to the database, as the database to which I made the query is Informix , the connection was made through ODBC , the problem that I have is when creating the json due to the variable types , I appreciate the help.

To perform the query and extract the mapping, I am guiding myself through this example that of enters gives me the following result:

Imported packages:

import (
    _"unicode/utf8"
    _"os"
    _ "github.com/alexbrainman/odbc"
    "database/sql"
    "fmt"
    "os"
    "time"
    "reflect"
    "log"
)

-code:

db, err := sql.Open("odbc", "DSN=" + host)
    if err != nil {
        fmt.Println("Could not connect to db:", err)
        os.Exit(1)
    }

    err = db.Ping()
    if err != nil {
        fmt.Println("got an error:", err)
        os.Exit(1)
    }
    /*SELECT*/
rows, err := db.Query("SELECT su.coduser AS id , TRIM(su.nomuser) AS user, s.fchven AS fch_ven, s.fecreg AS fch_registro FROM suser su JOIN sinfo s ON s.coduser = su.coduser WHERE su.nomuser=? AND su.pass=?",user_login,pass_login)
    cols, _ := rows.Columns()

    for rows.Next() {
        // Create a slice of interface{}'s to represent each column,
        // and a second slice to contain pointers to each item in the columns slice.
        columns := make([]interface{}, len(cols))
        columnPointers := make([]interface{}, len(cols))
        for i, _ := range columns {
            columnPointers[i] = &columns[i]
        }

        // Scan the result into the column pointers...
        if err := rows.Scan(columnPointers...); err != nil {
            //return err
        }

        // Create our map, and retrieve the value for each column from the pointers slice,
        // storing it in the map with the name of the column as the key.
        m := make(map[string]interface{})
        for i, colName := range cols {
            val := columnPointers[i].(*interface{})
            m[colName] = *val
        }

        // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
        fmt.Print(m)
    }

The query is fine, I actually do the cycle in case of several records, but when I print the map to see it in console, it shows me the following result:

map[id:769244 user:[65 100 109 105 110 95 117 115 101 114] fch_ven:2019-11-06 00:00:00 -0500 -05 fch_registro:2017-04-15 05:05:29 -0500 -05]2018/05/25 15:06:42 {0  <nil>  0   0 0   0 0                           0 0   0      }

I know I can do this:

 var name string
        if err := rows.Scan(&name); err != nil {
                log.Fatal(err)
        }

Create the variables and associate them, but I have problems with the fields that are of DATE and DATETIME , just do not return the information, so choose to use the example mentioned but I have problems with string , aside from when I do the storage in a variable var test string = m["user"].(string) . It just gives me an error in the line when I'm executing it, it just tells me that there is an error but it does not specify me.

    
asked by Andrés 25.05.2018 в 22:20
source

1 answer

2

Judging by the value shown in the console when you print the variable m the date type fields are returned as string or possibly time.Time , one way to confirm it would be:

import "reflect"
// ... codigo ...
for k, v := range m {
   fmt.Println(k, ":", v, " -> ", reflect.TypeOf(v))
}

We could know more if you mentioned the package you are using to interface with ODBC.

UPDATE

Based on your comment, you could get the date fields like this:

// ... codigo ...
var fechaVen, fechaReg time.Time
// ... 

I assigning them to columnPointers asi: columnPointers = append(columnPointers, fechaVen, fechaReg)

SECOND UPDATE

You can also use structs to perform the scan:

package main

import (
    "database/sql"
    "log"
    "time"

    _ "github.com/alexbrainman/odbc"
)

type userRecord struct {
    ID       string
    Nombre   string
    FechaVen time.Time
    FechaReg time.Time
}

func main() {

    const (
        host      = ""
        userLogin = ""
        passLogin = ""
    )

    db, err := sql.Open("odbc", "DSN="+host)
    if err != nil {
        log.Fatal("Could not connect to db:", err)
    }

    if err = db.Ping(); err != nil {
        log.Fatal("got an error:", err)
    }

    /*SELECT*/
    rows, err := db.Query('
    SELECT 
        su.coduser AS id,
        TRIM(su.nomuser) AS user,
        s.fchven AS fch_ven,
        s.fecreg AS fch_registro
    FROM 
        suser su JOIN sinfo s ON s.coduser = su.coduser 
    WHERE 
        su.nomuser=? AND su.pass=?',
        userLogin, passLogin)

    for rows.Next() {
        user := &userRecord{}

        // Scan the result into the column pointers...
        if err := rows.Scan(&user.ID, &user.Nombre, &user.FechaVen, &user.FechaReg); err != nil {
            log.Fatal(err)
        }

        // This will print each user
        log.Println(user)
    }
}
    
answered by 25.05.2018 / 23:42
source