1、简单web服务
- Go语言内置了Web服务;net/http 标准库中包含有关HTTP协议的所有功能。
- 注册请求处理函数 func ( w http.ResponseWriter , r *http.Request)
- 该函数接收两个参数:一个http.ResponseWriter 用于text/html响应。http.Request 其中包含有关此HTTP请求的所有信息,包括URL或者请求头字段之类的信息。
- 侦听http连接 http.ListenAndServe(":80",nil)
- 代码
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "你好,你的请求是 %s\n", r.URL.Path)
})
http.ListenAndServe(":80", nil)
}
2、Web开发框架-Gin
Gin 是一个 go 写的 web 框架,具有高性能的优点。官方地址:https://github.com/gin-gonic/gin
-
下载并安装
a: 如果比较慢,设置代理: https://goproxy.io/zh/docs/introduction.html
go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.io,direct
b:go get -u github.com/gin-gonic/gin
2.cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module
在使用 GOPROXY 的时候,开启了 GO111MODULE 导致包管理非官方所说的在 *$GOPATH\src* 而是去了 *$GOPATH\src\pkg* 目录下
go mod init gin
go mod edit -require github.com/gin-gonic/gin@latest
go mod vendor
3.示例
package main
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
type User struct {
ID int64
Name string
Age int
CreatedTime time.Time
UpdatedTime time.Time
IsDeleted bool
}
func main() {
//初始化引擎
r := gin.Default()
//简单的Get请求
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
//GET请求通过name获取参数 /user/test
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
//GET请求通过正常的URL获取参数 /getuser?id=2
r.GET("/getuser", func(c *gin.Context) {
rid := c.DefaultQuery("id", "1")
id, _ := strconv.ParseInt(rid, 10, 64)
user := User{ID: id, Age: 32, CreatedTime: time.Now(), UpdatedTime: time.Now(), IsDeleted: true}
c.JSON(http.StatusOK, user)
})
//POST请求通过绑定获取对象
r.POST("/adduser", func(c *gin.Context) {
var user User
err := c.ShouldBind(&user)
if err == nil {
c.JSON(http.StatusOK, user)
} else {
c.String(http.StatusBadRequest, "请求参数错误", err)
}
})
r.Run(":9002") // listen and serve on 0.0.0.0:9002
}
来源:oschina
链接:https://my.oschina.net/pengchanghua/blog/4699097