项目结构:
main.go:
package main
import (
"fmt"
"database/sql"
//_ "github.com/go-sql-driver/mysql"
"io"
"log"
"net/http"
//"io/ioutil"
"html/template"
"dao"
"strconv"
//"models"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, world!!!!")
}
func renderHtml(w http.ResponseWriter, tmpl string, locals map[string]interface{})(err error){
t, err := template.ParseFiles(tmpl + ".html")
if err != nil {
return err
}
err = t.Execute(w, locals)
return err
}
func listHandler(w http.ResponseWriter, r *http.Request){
locals := make(map[string]interface{})
users := dao.LoadInfo(db)
// users := []Info{}
//users = append(users, Info{121,"12313", 1})
locals["users"] = users
t, _ := template.ParseFiles( "list.html")
t.Execute(w, locals)
//locals := make(map[string]interface{})
//locals["infos"] = infos
//if err := renderHtml(w, "list", locals); err != nil {
// http.Error(w, err.Error(),
// http.StatusInternalServerError)
// }
// log.Print(" login index ")
// t,err := template.ParseFiles("list.html")
// if err != nil{
// http.Error(w,err.Error(),http.StatusInternalServerError)
// return
// }
// t.Execute(w,nil)
//return
}
func delHandler(w http.ResponseWriter, r *http.Request){
id := r.FormValue("id")
fmt.Println(id)
idint, _ := strconv.Atoi(id)
dao.DelInfo(db,idint)
//if err != nil{
// http.Error(w,err.Error(),http.StatusInternalServerError)
// return
//}
//t.Execute(w,nil)
http.Redirect(w,r,"/list",http.StatusFound)
//return
}
func addview(w http.ResponseWriter, r *http.Request){
t,err := template.ParseFiles("add.html")
if err != nil{
http.Error(w,err.Error(),http.StatusInternalServerError)
return
}
t.Execute(w,nil)
}
func addHandler(w http.ResponseWriter, r *http.Request){
name := r.FormValue("name")
itype := r.FormValue("itype")
fmt.Println(name)
fmt.Println(itype)
itypeint, _ := strconv.Atoi(itype)
dao.AddInfo(db,name,itypeint)
//idint, _ := strconv.Atoi(id)
//dao.DelInfo(db,idint)
//if err != nil{
// http.Error(w,err.Error(),http.StatusInternalServerError)
// return
//}
//t.Execute(w,nil)
http.Redirect(w,r,"/list",http.StatusFound)
//return
}
func indexHandler(w http.ResponseWriter, r *http.Request){
log.Print(" login index ")
t,err := template.ParseFiles("index.html")
if err != nil{
http.Error(w,err.Error(),http.StatusInternalServerError)
return
}
t.Execute(w,nil)
return
}
var db *sql.DB
func main() {
//user:= models.User{1,"212"}
// var info dao.Info
// info.ID = 121
// info.Name = "13221"
// info.Itype = 1
//p:= dao.Info{1,"nn" ,23}
db=dao.Initdb()
log.Print("start a web sevice!")
http.HandleFunc("/", indexHandler)
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/list", listHandler)
http.HandleFunc("/del", delHandler)
http.HandleFunc("/add", addHandler)
http.HandleFunc("/addview", addview)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
dao.go:
package dao
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"models"
)
type Info struct{
ID int
Name string
Itype int
}
func Initdb()(*sql.DB ){
fmt.Println("init db .....")
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
fmt.Println("db is error")
}
rows,err := db.Query("show tables")
for rows.Next(){
}
return db
}
func DelInfo(db *sql.DB,id int){
stmt,_:= db.Prepare("delete from msg_info where id =?")
stmt.Exec(id)
}
func AddInfo(db *sql.DB,name string, itype int){
stmt,_:= db.Prepare("insert msg_info(name,type) values(?,?) ")
stmt.Exec(name,itype)
}
func LoadInfo(db *sql.DB)([]models.Info){
rows,_ := db.Query("select * from msg_info")
results := []models.Info{}
for rows.Next(){
var ID int
var Name string
var Itype int
_ = rows.Scan(&ID,&Name,&Itype)
p:= models.Info{ID,Name ,Itype}
results=append(results,p)
}
return results
}
models.go:
package models
type User struct{
ID int
Name string
}
type Info struct{
ID int
Name string
Itype int
}
list.html:
<html>
<head>
<title>list</title>
</head>
<style type="text/css">
table{border-collapse:collapse;border-spacing:0;border-left:1px solid #888;border-top:1px solid #888;background:#efefef;}
th,td{border-right:1px solid #888;border-bottom:1px solid #888;padding:5px 15px;}
th{font-weight:bold;background:#ccc;}
</style>
<body>
<br><br>
<center><div style="font-size:30px">message list</div></center>
<br><br><br><br>
<div style="text-align:center"><a href="addview">add</a></ol>
</div>
<br>
<center>
<table width="70%" >
<tr>
<th>id</th>
<th>name</th>
<th>类型</th>
<th>删除</th>
</tr>
{{ range $.users}}
<tr>
<td>{{.ID}}</td>
<td>{{.Name}}</td>
<td>{{.Itype}}</td>
<td><a href="/del?id={{.ID}}">删除</a></td>
</tr>
{{end}}
</table>
</center>
</body>
</html>
add.list:
<html>
<head>
</head>
<body>
<br><br><br><br>
<center>
<div>add info<div>
<br><br><br>
<div style="text-align:center"><a href="list">list</a></div>
<br>
<form action="add" method="post" >
<div style="border:1px solid red; padding:10px;width:400px;padding-left: 200px;text-align:left">
<br><br>
<label for="name">name:</label>
<input type="text" name="name" />
<br><br>
<label for="itype">type:</label>
<select name="itype">
<option value ="1">Volvo</option>
<option value ="2">Saab</option>
<option value="2">Opel</option>
<option value="4">Audi</option>
</select>
<br><br>
<input type="submit" value="ok" style="width:100px;height:30px;" />
<br><br><br><br><br><br><br><br>
</div>
</form>
</center>
</body>
</html>
index.html:
<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor="#D1EEEE">
<br><br><br><br><br><br><br><br><br><br><br>
<center><div style="font-size:200px">
Welcome
</div>
</center>
<br><br>
<div style="text-align:center"><a href="addview">add</a></ol>
<div style="text-align:center"><a href="list">list</a></ol>
</body>
</html>
有疑问加站长微信联系(非本文作者)