一個超級簡單的 go Web 框架

夢想星辰大海發表於2020-07-03

開局先上程式碼:

package main

import (
    "bytes"
    "fmt"
    "github.com/buexplain/go-slim"
    "github.com/buexplain/go-slim/constant"
    "github.com/buexplain/go-slim/errors"
    "io"
    "log"
    "net/http"
)

//http應用
var app *slim.App

var addr string

func init() {
    //初始化app
    app = slim.New(true)
    addr = "127.0.0.1:1991"
}

func main() {
    //支援全域性中介軟體
    app.Use(func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) {
        log.Println("進入全域性中介軟體")
        ctx.Next()
    })

    app.Mux().Any("error", func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) error {
        act := r.Query("act", "abort")
        switch act {
        case "abort":
            return w.Abort(http.StatusBadRequest, http.StatusText(http.StatusBadRequest))
        case "panicStr":
            panic("test panic string")
        case "panicRawErr":
            panic(errors.New("test panic raw err"))
        case "panicMrKErrServer":
            panic(errors.MarkServer(errors.New("test panic mark server err")))
        case "panicMrKErrClient":
            panic(errors.MarkClient(errors.New("test panic mark client err")))
        case "jump":
            return w.Jump("/", "test jump to index", 5)
        case "returnRawErr":
            return errors.New("test return raw err")
        case "returnMrKErrServer":
            return errors.MarkServer(errors.New("test return mark server err"))
        case "returnMrKErrClient":
            return errors.MarkClient(errors.New("test return mark client err"))
        }
        return w.Abort(http.StatusBadRequest, http.StatusText(http.StatusBadRequest))
    })

    //支援響應緩衝
    app.Mux().Any("/", func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) error {
        buf := &bytes.Buffer{}
        _, _ = io.WriteString(buf, "<h3>點選如下按鈕進行測試,注意觀察命令列輸出資訊:</h3><hr>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/article/1'>全域性、組、xml響應</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/user/1'>全域性、組、路由中介軟體、json響應</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=abort'>abort</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=panicStr'>panic str</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=panicRawErr'>panic raw err</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=panicMrKErrServer'>panic server mrKErr</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=panicMrKErrClient'>panic client mrKErr</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=returnRawErr'>return raw err</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=returnMrKErrServer'>return server mrKErr</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=returnMrKErrClient'>return client mrKErr</a><br>")
        _, _ = io.WriteString(buf, "<a target='_blank' href='/error?act=jump'>jump</a><br>")
        //先寫資料
        _, err := io.Copy(w, buf)
        //再寫header頭
        w.WriteHeader(http.StatusOK)
        w.Header().Set(constant.HeaderContentType, constant.MIMETextHTMLCharsetUTF8)
        //返回錯誤
        return err
    })

    //支援組路由
    app.Mux().Group("", func() {
        //文章詳情
        app.Mux().Get("/article/:id", func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) error {
            type Result struct {
                Data string
                Code int
                Msg  string
            }
            return w.XML(http.StatusOK, Result{Data: r.Input("id", "0"), Code: 0, Msg: "success"})
        })
        //使用者詳情
        app.Mux().Get("/user/:id", func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) error {
            return w.Assign("code", 0).Assign("data", r.Input("id", "0")).Assign("msg", "success").JSON(http.StatusOK)
        }).Use(func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) { //支援路由中介軟體
            log.Println("進入路由中介軟體")
            ctx.Next()
        })
    }).Use(func(ctx *slim.Ctx, w *slim.Response, r *slim.Request) {
        log.Println("進入路由組中介軟體")
        ctx.Next()
    }).Regexp("id", `\d`) //用正則約束id

    //列印路由列表
    fmt.Println("http://" + addr + "/")
    fmt.Println(app.Mux().DumpRouteMap("main."))

    //啟動伺服器
    log.Fatalln(app.Run(addr))
}

然後再給連結:
框架倉庫:github.com/buexplain/go-slim
最後:
這個框架沒什麼測試用例,用到生產環境的話,有可能治好您的低血壓。
不過我用這個框架又擼了一個部落格出來,算是間接的測試用例了。
部落格倉庫:github.com/buexplain/go-blog
部署地址:www.fool127.com/
後臺地址:www.fool127.com/backend/sign
後臺賬號密碼:guest 123456

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章