Gin 框架的简单搭建

一、GIN概述

官方:Gin 是一个用 Go (Golang) 编写的 web 框架。 它是一个类似于 martini 但拥有更好性能的 API 框架,由于 httprouter,速度提高了近 40 倍

框架文档

二、Gin框架搭建

  1. 创建你的项目根目录并进入,如为 go-gin-demo

  2. 执行命令安装 gin

    go get -u github.com/gin-gonic/gin
  3. 拷贝一个初始模板到你的项目里

    curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
  4. go run main.go报错 模块找不到

    main.go:6:2: cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module
  5. 执行连个命令修正
    go-gin-demo 貌似可以随意取个人喜欢和项目名一样
    或者可以改成类似github.com/gin-gonic/gin 的路径

    go mod init go-gin-demo  
    go mod edit -require github.com/gin-gonic/gin@latest
  6. 执行 go run main.go 正常启动 默认8080 如果占用需要改为其他端口本人9090

    [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
    [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
    - using env:   export GIN_MODE=release
    - using code:  gin.SetMode(gin.ReleaseMode)
    [GIN-debug] GET    /ping                     --> main.setupRouter.func1 (3 handlers)
    [GIN-debug] GET    /user/:name               --> main.setupRouter.func2 (3 handlers)
    [GIN-debug] POST   /admin                    --> main.setupRouter.func3 (4 handlers)
    [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
    Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
    [GIN-debug] Listening and serving HTTP on :9090
  7. 测试响应,新建一个窗口

    curl 127.0.0.1:9090/ping     #响应  pong
    curl 127.0.0.1:9090/user/:peter  #响应 {"status":"no value","user":":peter"}

    至此,Gin 框架已经搭建好了!

本作品采用《CC 协议》,转载必须注明作者和本文链接
滴水穿石,石破天惊----晓疯子
zhaocrazy
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!