Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money
XDM was shared last time with a simple method used in the HTTP package in GO Web development, and finally there is a template, which is added here
Go straight to case
The template
- We’ll write a server demo in **main.go **, using the template to write the winter data to an HTML file
- Write an HTML file and set the data location for template injection
main.go
package main
import (
"fmt"
"html/template"
"net/http"
)
var myTemp *template.Template
type Person struct {
Name string
Title string
Age int
}
// Start processing data and responding
func userInfo(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
var pp []Person
// Simple simulation data
p1 := Person{
Name: "XMT 1",
Title: "Exhibit 1",
Age: 18,
}
p2 := Person{
Name: "XMT 2",
Title: "Exhibit 2",
Age: 15,
}
p3 := Person{
Name: "XMT 3",
Title: "Exhibit 3",
Age: 29,
}
pp = append(pp, p1, p2, p3)
// Write data to the template
err := myTemp.Execute(w, pp)
iferr ! =nil {
fmt.Println("The Execute err; %v", err)
return}}func main(a) {
// Initialize the template
var err error
myTemp, err = template.ParseFiles("./index.html")
iferr ! =nil {
fmt.Println("ParseFiles err ;%v", err)
return
}
// Register functions that process templates and enable listening
http.HandleFunc("/", userInfo)
err = http.ListenAndServe("0.0.0.0:9999".nil)
iferr ! =nil {
fmt.Println("ListenAndServe err ;%v", err)
return}}Copy the code
index.html
<html>
<head>
</head>
<body>
<p>hello world</p>
<table border="1" align="center" width="600px">
<tr>
<td>{{.Name}}</td> <td>{{.Age}}</td><td>{{.Title}}</td>
</tr>
</table>
</body>
</html>
Copy the code
The above code is also relatively simple, directly run main.go can start the server, we only need to access in the browser
http://localhost:8888/
Copy the code
You can see the effect of our HTML display, the data is dynamic
Also, let’s take a look at the mysql database used in Go Web
Mysql
Connecting to a Database
Operation database, basically is the following several steps
-
Open the MySQL database and ping the MySQL database
-
To write mysql code, you must import this package _ “github.com/go-sql-driver/mysql”, you need to execute mysql init function first
-
Enter your own mysql password. If you cannot remember the password, set the password to 123456 for learning and practice
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" // Call the initialization function after the exception is commented out ) func main(a) { // If you want to connect to the mysql database, you must ping the mysql database db, err := sql.Open("mysql"."Root: XXXXXX @ TCP/go_test (127.0.0.1:3306)? charset=utf8mb4") iferr ! =nil { fmt.Println("Open err : ", err) return } err = db.Ping() iferr ! =nil { fmt.Println("Ping err : ", err) return } db.Close() } Copy the code
Here we can see charset= UTf8MB4, here we set the character encoding format to UTF8MB4, mainly used for
It should be noted that basically our mysql encoding is set to the UTF8MB4 character set because it supports 4-byte Unicode characters
In the early days, when Unicode was not perfect, UTF8 was used, requiring only up to three bytes to represent Unicode characters
increase
Do a data add operation to insert data into the database
- Here we use placeholders to insert data
- Fill in the standard SQL statement in the sqlInfo variable
func insertPiceInfo(db *sql.DB) {
/ /? As a placeholder
sqlInfo := "insert into user(name,age)values(? ,?) "
ret, err := db.Exec(sqlInfo, "xxx".19)
iferr ! =nil {
fmt.Println("Exec err : ", err)
return
}
// Insert the id of data
id, err := ret.LastInsertId()
iferr ! =nil {
fmt.Println("LastInsertId err : ", err)
return
}
fmt.Println("LastInsertId == ", id)
// Number of rows affected by this operation
rows, err := ret.RowsAffected()
iferr ! =nil {
fmt.Println("RowsAffected err : ", err)
return
}
fmt.Println("rows == ", rows)
}
Copy the code
After the insert statement is executed, you can obtain the ID of the successful data insertion and the number of rows affected by the data insertion according to the insert result
delete
Deleting data is easier, and again we can get the result of deleting data to get the number of rows that are affected and so on
func deletePiceInfo(db *sql.DB) {
/ /? As a placeholder
sqlInfo := "delete from user where id= xx "
ret, err := db.Exec(sqlInfo)
iferr ! =nil {
fmt.Println("Exec err : ", err)
return
}
// Number of rows affected by this operation
rows, err := ret.RowsAffected()
iferr ! =nil {
fmt.Println("RowsAffected err : ", err)
return
}
fmt.Println("rows == ", rows)
}
Copy the code
Modify the
func updatePiceInfo(db *sql.DB) {
/ /? As a placeholder
sqlInfo := "update user set name='xxx' where id=xx"
ret, err := db.Exec(sqlInfo)
iferr ! =nil {
fmt.Println("Exec err : ", err)
return
}
// Number of rows affected by this operation
rows, err := ret.RowsAffected()
iferr ! =nil {
fmt.Println("RowsAffected err : ", err)
return
}
fmt.Println("rows == ", rows)
}
Copy the code
See, modify operations and other add, delete operations similar, written basically the same, but also relatively simple
The query
Query operation, should be used in the database operation relatively more operations, go operation mysql query, simple there are two points to note:
- The rows obtained after Query need to remember close
- Remember to call the Scan method immediately after the query data is called, otherwise the database link held will not be released
type myInfo struct{
id int
name string
age int
}
func selectInfo(db *sql.DB) {
sqlInfo := "select * from user"
rows, err := db.Query(sqlInfo)
iferr ! =nil {
fmt.Println("Exec err : ", err)
return
}
// Very important: Close rows to release the database link held
defer rows.Close()
// Output the number of rows queried
for rows.Next(){
var u myInfo
rows.Scan(&u.id,&u.name,&u.age)
fmt.Printf("id = %d, name = %s, age = %d\n",u.id,u.name,u.age)
}
}
Copy the code
Welcome to like, follow and favorites
Friends, your support and encouragement, I insist on sharing, improve the quality of the power
All right, that’s it for this time
Technology is open, our mentality, should be more open. Embrace change, live in the sun, and strive to move forward.
I am Nezha, welcome to like, see you next time ~