Go Web Example

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Project structure:


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:

<title>list</title>


<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;p adding: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> Type </th>

<th> Delete </th>

</tr>

{{range $.users}}


<tr>

<td>{{.ID}}</td>

<td>{{. Name}}</td>

<td>{{. Itype}}</td>

<td><a href= "/del?id={{.id}" > Delete </a></td>

</tr>

{{end}}

</table>

</center>


</body>

Add.list:


<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>

Index.html:

<title>Welcome</title>

<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>


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.