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成功"))
} 相关推荐
houmenghu 2020-11-17
kentrl 2020-11-10
jincheng 2020-09-01
Blueberry 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
阳光之吻 2020-08-03
PkJY 2020-07-08
hzyuhz 2020-07-04
服务器端攻城师 2020-06-26
阳光岛主 2020-06-25
笨重的蜗牛 2020-06-20
xuanwenchao 2020-06-14
Lophole 2020-06-13
明瞳 2020-06-12
songerxing 2020-06-11
明瞳 2020-06-08