Golang保存PostgreSQL数据至结构

具体代码如下:

package main

import (
    "database/sql"
    "fmt"
    "log"
    "reflect"
    "net/http"

    _ "github.com/lib/pq"
)

type sys_user struct {
    su_id      int
    su_name    string
    su_gender  string
    su_age     int
    su_address string
    su_im      string
    su_regtime string
}

func main() {
    var su []sys_user
    var Suaction sys_user = sys_user{}

    db, err := sql.Open("postgres", "user=admin password=123456 dbname=test sslmode=disable")
    if err != nil {
        log.Println("Open error.")
        log.Println(err)
    }
    defer db.Close()

    rows, err := db.Query("SELECT * FROM sys_user")
    if err != nil {
        log.Println("Query error.")
        log.Println(err)
    }

    for rows.Next() {
        err = rows.Scan(
            &Suaction.su_id,
            &Suaction.su_name,
            &Suaction.su_gender,
            &Suaction.su_age,
            &Suaction.su_address,
            &Suaction.su_im,
            &Suaction.su_regtime,
        )
        if err != nil {
            log.Println("Scan error.")
            log.Println(err)
        }

        su = append(su, Suaction)
    }

    for _, v := range su {
        v1 := reflect.ValueOf(v)
        for i := 0; i < v1.NumField(); i++ {
            fmt.Printf("%40v |", v1.Field(i))
        }
        fmt.Println()
    }
    http.HandleFunc("/readcookie", ReadCookie)
    http.HandleFunc("/writecookie", WriteCookie)
    http.HandleFunc("/deletecookie", DeleteCookie)
    http.ListenAndServe(":9090", nil)
}

func WriteCookie(w http.ResponseWriter,r *http.Request)  {
    //创建新的本地cookie
    cookie := http.Cookie{Name:"merrynuts",Value:"education",Path:"/",MaxAge:86400}
    http.SetCookie(w,&cookie)
    w.Write([]byte("设置cookie成功"))
}

func ReadCookie(w http.ResponseWriter,r *http.Request)  {
    //读取cookie
    cookie,err := r.Cookie("merrynuts")
    if err == nil {
        cookieValue := cookie.Value
        //将数据写入http连接中
        w.Write([]byte("cookie的值为:"+cookieValue))
    }else {
        w.Write([]byte("读取cookie出错:"+err.Error()))
    }
}

func DeleteCookie(w http.ResponseWriter,r *http.Request)  {
    cookie := http.Cookie{Name:"merrynuts",Path:"/",MaxAge:-1}
    http.SetCookie(w,&cookie)
    w.Write([]byte("删除cookie成功"))
}

相关推荐