Gin 框架的簡單搭建

zhaocrazy發表於2022-01-01

一、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 協議》,轉載必須註明作者和本文連結
滴水穿石,石破天驚----馬乂

相關文章