Gin框架介绍及使用
Gin是一个用Go语言编写的web框架。它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter,速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin
- go env -w GO111MODULE=on
-
go env -w GOPROXY=https://goproxy.io,direct
-
安装 gin 包 go get github.com/gin-gonic/gin
-
在项目命令行下执行 go mod init gin-01
go mod init 项目名
- 再执行 go mod tidy
创建main.go以及 index.html文件
main.go
package main
import (
"fmt"
"html/template"
"net/http"
)
func main() {
http.HandleFunc("/", hello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Println("HTTP server failed,err:", err)
return
}
}
func hello(w http.ResponseWriter, r *http.Request) {
// 解析指定文件生成模板对象
tmpl, err := template.ParseFiles("./index.html")
if err != nil {
fmt.Println("create template failed, err:", err)
return
}
// 利用给定数据渲染模板,并将结果写入w
tmpl.Execute(w, "王子文")
}
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello</title>
</head>
<body>
<p>Hello {{.}}</p>
</body>
</html>
在命令行运行run
go run main.go
结果
要点
① 用到了 “html/template” 模板包
② 用到了 “net/http” http包