or rang語句 :實現遍歷數據功能,可以實現對數組、Slice、Map、或Channel等數據結構
. 表示每次迭代循環中的元素
main.go源碼及解析
package main
import (
"net/http"
"text/template"
)
func Index(w http.ResponseWriter, r *http.Request) {
//ParseFiles從"index.html"中解析模板。
//如果發生錯誤,解析停止,返回的*Template為nil。
//當解析多個文件時,如果文件分布在不同目錄中,且具有相同名字的,將以最后一個文件為主。
files, _ := template.ParseFiles("index.html")
//聲明變量b,類型為字符串切片,有三個內容
b := []string{"張無忌", "張三豐", "張翠山"}
//聲明變量b,類型為字符串切片,沒有內容,是為了else示例
//b := []string{}
//Execute負責渲染模板,并將b寫入模板。
_ = files.Execute(w, b)
//w.Write([]byte("/index"))
}
func main() {
http.HandleFunc("/index", Index)
_ = http.ListenAndServe("", nil)
}
模板index.html的源碼及解析
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<pre>
{{range .}}
{{.}}
{{else}}
None
{{end}}
</pre>
</body>
</html>
測試http服務,推薦使用httptest進行單元測試
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestIndex(t *testing.T) {
//初始化測試服務器
handler := http.HandlerFunc(Index)
app := httptest.NewServer(handler)
defer app.Close()
//測試代碼
//發送http.Get請求,獲取請求結果response
response, _ := http.Get(app.URL + "/index")
//關閉response.Body
defer response.Body.Close()
//讀取response.Body內容,返回字節集內容
bytes, _ := ioutil.ReadAll(response.Body)
//將返回的字節集內容通過string()轉換成字符串,并顯示到日志當中
t.Log(string(bytes))
}
執行結果
ain.go
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
//加載首頁的頁面
func indexHandler(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadFile("./static/index.html")
if err != nil {
io.WriteString(w, "internel server error")
return
}
io.WriteString(w, string(data))
//w.Write(data)
}
//接收表單參數
func userHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析參數,默認是不會解析的
if r.Method == "GET" { //GET請求的方法
username := r.Form.Get("username") //必須使用雙引號, 注意: 這里的Get 不是指只接收GET請求的參數, 而是獲取參數
password := r.Form.Get("password")
//limit, _ := strconv.Atoi(r.Form.Get("limit")) //字符串轉整數的接收方法
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
} else if r.Method == "POST" { //POST請求的方法
username := r.Form.Get("username") //必須使用雙引號, 注意: POST請求, 也是用Get方法來接收
password := r.Form.Get("password")
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
}
}
//文件上傳
func uploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析參數,默認是不會解析的
if r.Method == "GET" { //GET請求的方法
data, err := ioutil.ReadFile("./static/upload.html")
if err != nil {
io.WriteString(w, "internel server error")
return
}
io.WriteString(w, string(data))
} else if r.Method == "POST" { //POST請求的方法
// 接收文件流及存儲到本地目錄
file, head, err := r.FormFile("image") //接收文件域的方法
if err != nil {
fmt.Printf("Failed to get data, err:%s\n", err.Error())
return
}
defer file.Close()
newFile, err := os.Create("C:/tmp/" + head.Filename) //創建文件
if err != nil {
fmt.Printf("Failed to create file, err:%s\n", err.Error())
return
}
defer newFile.Close()
FileSize, err := io.Copy(newFile, file) //拷貝文件
if err != nil {
fmt.Printf("Failed to save data into file, err:%s\n", err.Error())
//http.Redirect(w, r, "/static/index.html", http.StatusFound) //重定向的方法
return
}
io.WriteString(w, "上傳成功"+strconv.FormatInt(FileSize, 10)) //int64轉換成string
}
}
func main() {
// 靜態資源處理
http.Handle("/static/",
http.StripPrefix("/static/",
http.FileServer(http.Dir("./static"))))
// 動態接口路由設置
http.HandleFunc("/index", indexHandler)
http.HandleFunc("/user", userHandler)
http.HandleFunc("/upload", uploadHandler)
// 監聽端口
fmt.Println("上傳服務正在啟動, 監聽端口:8080...")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Failed to start server, err:%s", err.Error())
}
}
static/upload.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="image" value="upload" />
<input type="submit" value="上傳"/>
</form>
</body>
</html>
static/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>這是首頁的內容</p>
</body>
</html>
D:\work\src>go run main.go
上傳服務正在啟動, 監聽端口:8080...
訪問方式:
http://localhost:8080/upload
么是設計模式?
設計模式是一套理論, 由軟件界先輩們總結出的一套可以反復使用的經驗, 可以提高代碼可重用性, 增強系統可維護性, 以及巧妙解決一系列邏輯復雜的問題(運用套路).
1995 年,艾瑞克·伽馬(ErichGamma)、理査德·海爾姆(Richard Helm)、拉爾夫·約翰森(Ralph Johnson)、約翰·威利斯迪斯(John Vlissides)等 4 位作者合作出版了《設計模式:可復用面向對象軟件的基礎》(Design Patterns: Elements of Reusable Object-Oriented Software)一書,在本教程中收錄了 23 個設計模式,這是設計模式領域里程碑的事件,導致了軟件設計模式的突破。這 4 位作者在軟件開發領域里也以他們的“四人組”(Gang of Four,GoF)匿名著稱.
Go 語言設計模式的實例代碼 + 代碼圖解
項目地址:https://github.com/ssbandjl/golang-design-pattern
簡單工廠模式(Simple Factory)
工廠方法模式(Factory Method)
抽象工廠模式(Abstract Factory)
創建者模式(Builder)
原型模式(Prototype)
單例模式(Singleton)
適配器模式(Adapter)
享元模式(Flyweight)
裝飾模式(Decorator)
參考文檔
廖雪峰:
https://www.liaoxuefeng.com/wiki/1252599548343744/1281319417937953
圖解設計模式: http://c.biancheng.net/view/1397.html
golang-design-patttern: https://github.com/senghoo/golang-design-pattern
END已結束
歡迎大家留言, 訂閱, 交流哦!
往期回顧
[翻譯自官方]什么是RDB和AOF? 一文了解Redis持久化!
Golang GinWeb框架9-編譯模板/自定義結構體綁定/http2/操作Cookie/完結
Golang GinWeb框架8-重定向/自定義中間件/認證/HTTPS支持/優雅重啟等
Golang GinWeb框架7-靜態文件/模板渲染
Golang GinWeb框架6-XML/JSON/YAML/ProtoBuf等渲染
Golang GinWeb框架5-綁定請求字符串/URI/請求頭/復選框/表單類型
Golang GinWeb框架4-請求參數綁定和驗證
Golang GinWeb框架3-自定義日志格式和輸出方式/啟禁日志顏色
Golang GinWeb框架2-文件上傳/程序panic崩潰后自定義處理方式
Golang GinWeb框架-快速入門/參數解析
Golang與亞馬遜對象存儲服務AmazonS3快速入門
Golang+Vue實現Websocket全雙工通信入門
GolangWeb編程之控制器方法HandlerFunc與中間件Middleware
Golang連接MySQL執行查詢并解析-告別結構體
Golang的一種發布訂閱模式實現
Golang 并發數據沖突檢測器(Data Race Detector)與并發安全
Golang"驅動"MongoDB-快速入門("快碼加鞭")
點擊 "閱讀原文"獲得更好閱讀體驗哦!點擊[在看], 推薦給其他小伙伴哦!
*請認真填寫需求信息,我們會在24小時內與您取得聯系。