美文网首页
Golang轻量级框架 net/http Gin使用

Golang轻量级框架 net/http Gin使用

作者: for笑 | 来源:发表于2021-12-23 19:09 被阅读0次

    引入gin


    image.png
    go get -u github.com/gin-gonic/gin
    
    image.png

    要是安装太慢或失败,添加代理重新下载安装

    go env -w GO111MODULE=on
    #下面二选一
    go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/
    go env -w GOPROXY=https://goproxy.io,direct
    
    go get -u github.com/gin-gonic/gin
    

    安装显示


    image.png

    可通过go env 查看配置的两个代理变量


    image.png

    报错:gotest.go:4:2: cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module

    go mod init gin
    
    go mod edit -require github.com/gin-gonic/gin@latest
    

    报错:$GOPATH/go.mod exists but should not

    产生原因:开启模块支持后,并不能与GOPATH共存,所以把项目从GOPATH中移出即可

    image.png
    package main
    
    import (
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        // 创建一个默认的路由引擎
        router := gin.Default()
        // GET:请求方式;/hello:请求的路径
        // 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
        router.GET("/hello", func(c *gin.Context) {
            // c.JSON:返回JSON格式的数据
            c.JSON(200, gin.H{
                "message": "Hello world!",
            })
        })
        router.GET("/name", func(c *gin.Context) {
            c.String(200,"hello world")
        })
        // 启动HTTP服务,默认在0.0.0.0:8080启动服务
        router.Run(":8001")
    }
    
    
    image.png

    请求返回结果


    image.png

    相关文章

      网友评论

          本文标题:Golang轻量级框架 net/http Gin使用

          本文链接:https://www.haomeiwen.com/subject/mmtkqrtx.html