go web 例子

昏鸦 · · 4160 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

项目结构:


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>



有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:昏鸦

查看原文:go web 例子

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

4160 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传