go web的两个入门例子

tech2025-10-02  2

package main import ( "fmt" "html/template" "net/http" //导入模块 ) func test(w http.ResponseWriter,r *http.Request){//定义view函数,此函数传参格式唯一, t,err:=template.New("test.tmpl").ParseFiles("./test.tmpl") if err !=nil{ fmt.Println("you have an error") } t.Execute(w,nil) } func main() { http.HandleFunc("/",test) http.ListenAndServe(":8080",nil) }

第二种方式使用gin框架,在使用之前,需要先下载gin

go get github/gin-gonic/gin //如果不能正常下载,需要使用代理

代理链接: Goproxy中国 按照他所说的方法配置,配置之后,再进行下载

package main import "github.com/gin-gonic/gin"导入gin模块 //导入之后,仍需要在go.mod中导入,在命令行中进入项目文件夹,执行go mod tidy,便会根据你导入的内容进行自动导入 func main() { r := gin.Default()//创建对象 r.LoadHTMLFiles("./templates/test.tmpl","./templates/testy.tmpl")//加载模板 r.GET("/test", func(c *gin.Context) {//get请求时,对应执行的函数,第一个参数为 c.HTML(200, "test.tmpl", gin.H{//第一个参数为状态码,第二个参数为需要渲染的html,第三个参数为传递的数据 "Message": "i success",//以键值对的形式 }) }) r.POST("/test", func(c *gin.Context) {//对应post请求时,调用的函数 c.HTML(200, "testy.tmpl", gin.H{//同上 "Message": "this is post", }) }) r.Run(":8080")//传参为端口号 }
最新回复(0)