虎踞龙盘今胜昔,天翻地覆慨而慷
70多年前,伟大领袖在号召百万雄狮打过长江去的前夜,兴之所至,大笔一挥,便留下了这首气势恢宏、磅礴大气的诗词。70多年过去了,蒋家王朝的统治早已经消失在浩瀚的历史烟云中,但是前进的征途上敌对势力的封锁从来未曾松懈过。在核心的关键技术领域我们始终处于一种被人掐脖子的状态,不过好在从今年开始,操作系统方面可以减去一项,如果说别的企业要来搞这块硬骨头,我是大概率不看好的,但是华为,我相信肯定能做成。
go的web开发
go的web开发其实相比与其他的编程语言容易了很多,一来是因为go本身的语法比较简单,二来是因为一些重要的跟web相关的库都已经内置了,除此之外一些第三方的web开发框架也算是比较多的,学习成本也比较少,综合下来而言,web开发在门槛上降低了很多。
1、简单的api搭建
func Hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world!")
}
func main() {
http.HandleFunc("/hello", Hello)
http.ListenAndServe(":9000", nil)
}
//配置中间件
func logging(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
f(w, r)
}
}
func foo(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
http.HandleFunc("/foo", logging(foo))
http.HandleFunc("/bar", logging(bar))
http.ListenAndServe(":8080", nil)
}
2、表单操作
//前端页面
<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
//后端代码
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
log.Println(t.Execute(w, nil))
}else{
err := r.ParseForm()
if err != nil {
log.Fatal("ParseForm:", err)
}
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
}
}
func main() {
http.HandleFunc("/", sayhelloName)
http.HandleFunc("/login", login)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
//其他的案例
<h1>{{.PageTitle}}</h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li class="done">{{.Title}}</li>
{{else}}
<li>{{.Title}}</li>
{{end}}
{{end}}
</ul>
type Todo struct {
Title string
Done bool
}
type TodoPageData struct {
PageTitle string
Todos []Todo
}
func main() {
tmpl := template.Must(template.ParseFiles("layout.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := TodoPageData{
PageTitle: "My TODO list",
Todos: []Todo{
{Title: "Task 1", Done: false},
{Title: "Task 2", Done: true},
{Title: "Task 3", Done: true},
},
}
tmpl.Execute(w, data)
})
http.ListenAndServe(":80", nil)
}
3、数据库交互
import (
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:root@/test?charset=utf8")
checkErr(err)
/*****************************数据库中插入数据***********************************/
/*
stmt, err := db.Prepare("INSERT userinfo SET username=?, department=?, created=?")
checkErr(err)
res, err := stmt.Exec("张三", "技术部", "2021-06-01")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
*/
/*****************************数据库中修改数据***********************************/
/*
stmt, err := db.Prepare("UPDATE userinfo SET username=? where uid=?")
checkErr(err)
res, err := stmt.Exec("王五", 1)
checkErr(err)
affectRow, err := res.RowsAffected()
checkErr(err)
fmt.Println(affectRow)
*/
/*****************************数据库中删除数据***********************************/
/*
stmt, err := db.Prepare("DELETE FROM userinfo WHERE uid=?")
checkErr(err)
res, err := stmt.Exec(1)
checkErr(err)
affectRow, err := res.RowsAffected()
checkErr(err)
fmt.Println(affectRow)
*/
/*****************************数据库中查询数据***********************************/
/*
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
for rows.Next() {
var uid int
var username string
var department string
var created string
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
*/
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
4、针对cookie的操作
func setCookie(w http.ResponseWriter, r *http.Request) {
expiration := time.Now()
expiration = expiration.AddDate(1, 0, 0)
cookie := http.Cookie{Name: "ZhaoZhao", Value: "6666", Expires: expiration}
http.SetCookie(w, &cookie)
}
func readCookie(w http.ResponseWriter, r *http.Request) {
//cookie, _ := r.Cookie("ZhaoZhao")
//fmt.Fprintln(w, cookie)
for _, cookie := range r.Cookies() {
fmt.Fprintln(w, cookie.Name, ":" ,cookie.Value)
}
}
func main() {
http.HandleFunc("/setCookie", setCookie)
http.HandleFunc("/readCookie", readCookie)
http.ListenAndServe(":8090", nil)
}
5、针对session的处理
参考文献:https://learnku.com/docs/build-web-application-with-golang/how-062-go-uses-session/3190
小结
go的web相关的内容大概就是这些,总体而言写的比较乱,后续如果有时间可能会加以优化,同时从这篇之后可能会讲解一些常用的框架比如gin、gorm以及一些常见中间件的整合。