go web 例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

項目結構:


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>


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.