美文网首页
Gin框架与《Web Development with Go》实

Gin框架与《Web Development with Go》实

作者: Cyberpunk_ZYM | 来源:发表于2017-06-08 17:30 被阅读0次

    应用的处理函数

    src/taskmanager2/controllers2


    taskmanager-controller2.png

    显示HTTP Errors的助手

    src/taskmanager2/common2/utils.go

    package common2
    
    import (
        "encoding/json"
        "os"
        "log"
    
        "gopkg.in/gin-gonic/gin.v1"
        "net/http"
    )
    
    type (
        appError struct {
            Error string `json:"error"`
            Message string `json:"message"`
            HttpStatus int `json:"status"`
        }
        errorResource struct {
            Data appError `json:"data"`
        }
        ...
    )
    
    func DisplayAppError(c *gin.Context, handlerError error, message string, code int) {
        errObj := appError{
            Error:      handlerError.Error(),
            Message:    message,
            HttpStatus: code,
        }
        //log.Printf("AppError]: %s\n", handlerError)
        Error.Printf("AppError]: %s\n", handlerError)
    
        c.JSON(http.StatusFound, errorResource{Data: errObj})
    }
    
    ...
    

    为一个http请求的周期处理数据

    src/taskmanager2/controllers2/context.go
    注意:现在标准库中已有context包,日后此处再改进。

    package controllers2
    
    import (
        "gopkg.in/mgo.v2"
        "taskmanager2/common2"
    )
    
    type Context struct {
        MongoSession *mgo.Session
    }
    
    func (c *Context) Close() {
        c.MongoSession.Close()
    }
    
    func (c *Context) DbCollection(name string) *mgo.Collection {
        return c.MongoSession.DB(common2.AppConfig.Database).C(name)
    }
    
    func NewContext() *Context {
        session := common2.GetSession().Copy()
        context := &Context{
            MongoSession: session,
        }
        return context
    }
    

    相关文章

      网友评论

          本文标题:Gin框架与《Web Development with Go》实

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