具体代码如下:
1 package main 2 3 import ( 4 "database/sql" 5 "fmt" 6 "log" 7 "reflect" 8 "net/http" 9 10 _ "github.com/lib/pq" 11 ) 12 13 type sys_user struct { 14 su_id int 15 su_name string 16 su_gender string 17 su_age int 18 su_address string 19 su_im string 20 su_regtime string 21 } 22 23 func main() { 24 var su []sys_user 25 var Suaction sys_user = sys_user{} 26 27 db, err := sql.Open("postgres", "user=admin password=123456 dbname=test sslmode=disable") 28 if err != nil { 29 log.Println("Open error.") 30 log.Println(err) 31 } 32 defer db.Close() 33 34 rows, err := db.Query("SELECT * FROM sys_user") 35 if err != nil { 36 log.Println("Query error.") 37 log.Println(err) 38 } 39 40 for rows.Next() { 41 err = rows.Scan( 42 &Suaction.su_id, 43 &Suaction.su_name, 44 &Suaction.su_gender, 45 &Suaction.su_age, 46 &Suaction.su_address, 47 &Suaction.su_im, 48 &Suaction.su_regtime, 49 ) 50 if err != nil { 51 log.Println("Scan error.") 52 log.Println(err) 53 } 54 55 su = append(su, Suaction) 56 } 57 58 for _, v := range su { 59 v1 := reflect.ValueOf(v) 60 for i := 0; i < v1.NumField(); i++ { 61 fmt.Printf("%40v |", v1.Field(i)) 62 } 63 fmt.Println() 64 } 65 http.HandleFunc("/readcookie", ReadCookie) 66 http.HandleFunc("/writecookie", WriteCookie) 67 http.HandleFunc("/deletecookie", DeleteCookie) 68 http.ListenAndServe(":9090", nil) 69 } 70 71 func WriteCookie(w http.ResponseWriter,r *http.Request) { 72 //创建新的本地cookie 73 cookie := http.Cookie{Name:"merrynuts",Value:"education",Path:"/",MaxAge:86400} 74 http.SetCookie(w,&cookie) 75 w.Write([]byte("设置cookie成功")) 76 } 77 78 func ReadCookie(w http.ResponseWriter,r *http.Request) { 79 //读取cookie 80 cookie,err := r.Cookie("merrynuts") 81 if err == nil { 82 cookieValue := cookie.Value 83 //将数据写入http连接中 84 w.Write([]byte("cookie的值为:"+cookieValue)) 85 }else { 86 w.Write([]byte("读取cookie出错:"+err.Error())) 87 } 88 } 89 90 func DeleteCookie(w http.ResponseWriter,r *http.Request) { 91 cookie := http.Cookie{Name:"merrynuts",Path:"/",MaxAge:-1} 92 http.SetCookie(w,&cookie) 93 w.Write([]byte("删除cookie成功")) 94 }