GoLearning/Docs/创建第一个Go Web程序.md

56 lines
1.4 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 创建第一个Go Web程序
创建第一个最简单的Go Web程序需要准备以下几个文件。`main.go`如下所示:
```go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 创建Gin引擎
r := gin.Default()
// 配置静态文件路径
//r.Static("/static", "./static")
r.LoadHTMLGlob("static/*")
// 定义GET请求处理程序返回HTML响应
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
// c.JSON(http.StatusOK, gin.H{
// "message": "Hello, World!",
// })
})
// 启动HTTP服务器
r.Run(":8080")
}
```
在上面的`main.go`中我们启动了服务器并渲染了`index.html`。但是,由于我们引入了第三方的库如`Gin`,所以我们需要在`go.mod`文件中描述我们需要引用的第三方包。`go.mod`如下所示:
```go
module example.com/myapp
go 1.16
require (
github.com/gin-gonic/gin v1.7.1
github.com/go-sql-driver/mysql v1.6.0
github.com/jinzhu/gorm v1.9.16
)
```
当我们输入命令`go run main.go`的时候,命令行会提示出错找不到`go.sum`。这往往是因为我们没有下载依赖库。我们执行命令:
```shell
go mod download github.com/gin-gonic/gin
```
此时,即可对应生成`go.sum`文件,以及启动`main.go`程序。我们在浏览器中输入`127.0.0.1:8080`即可看到网站。