GO的Gin后端框架

1.Gin

Go 语言中,Gin 是一个流行的 Web 框架,它提供了一种简单、快速和高效的方式来构建 Web 应用。Gin 使用类似于 Martini 的 API,但是性能更好(归功于它基于 radix 树的路由),并且拥有更好的性能基准。

2.Gin使用

2.1 启动

 package main

import (
    "GoGin/routers"
    "github.com/gin-gonic/gin"
)

func main() {

    r := gin.Default()
    r.LoadHTMLGlob("templates/*")

    routers.LoadBlog(r)
    routers.LoadShop(r)
    routers.Test(r)
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

2.2路由与处理请求

package routers

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
)

//get请求,获取url参数
func doGet(c *gin.Context) {
    aid := c.Query("aid")
    fmt.Println(aid)
    data := map[string]interface{}{"name": "lijun", "age": 18}
    c.JSON(http.StatusOK, gin.H{
        "data": data,
    })
}

//post请求,获取表单数据
func doPost(c *gin.Context) {
    username := c.PostForm("username")
    password := c.PostForm("password")
    c.JSON(http.StatusOK, gin.H{
        "message":  "test_post",
        "username": username,
        "password": password,
        "code":     200,
    })
}

// Test is a test function.
// Test test接口与处理映射
func Test(e *gin.Engine) {
    e.GET("/index", index)
    e.GET("/ping", doGet)
    e.POST("/test_post", doPost)
    e.POST("/uploads", uploads)
}

// index handles the index route.
//后端渲染
func index(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl", gin.H{
        "title": "hello",
    })
}

// uploads handles the file uploads.
//上传多个文件
func uploads(c *gin.Context) {
    // Multipart form
    form, _ := c.MultipartForm()
    files := form.File["upload[]"]

    for _, file := range files {
        log.Println(file.Filename)
        dst := "./upload/" + file.Filename
        // 上传文件至指定目录
        err := c.SaveUploadedFile(file, dst)
        if err != nil {
            c.String(400, "failed!")
            return
        }
    }
    c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇