doulan0297 2018-06-09 13:50
浏览 69
已采纳

仅将接口的方法参数传递一次?

I'm trying to figure out a way to make my code shorter and simpler, by only calling the parameters for interface methods once in the parent struct(?)

First the route defining:

func Init() {
    // Create route
    r := mux.NewRouter()

    // Default routes
    router.Route("/", webtest.TestController{}, r)

    // Serve the routes
    router.Serve(r)
}

Then the functions for it:

type Controller struct {
    ControllerInterface
}

type ControllerInterface interface {
    Get(w http.ResponseWriter, r *http.Request)
}

func Route(path string, ct interface{}, r *mux.Router) {
    if c, ok := ct.(controllers.ControllerInterface); ok {
        r.HandleFunc(path, http.HandlerFunc(c.Get)).Methods("GET")
    }
}

Then I call the route with

type TestController struct {
    controllers.Controller
}

func (c TestController) Get(w http.ResponseWriter, r *http.Request) {
    println("Hello World")
}

As you can see I have to have w http.ResponseWriter, r *http.Request everywhere, or the routes would not work. Is there any way I can include these params in the parent struct (or similar) so I don't have to include it everytime?

  • 写回答

2条回答 默认 最新

  • duanfu3390 2018-06-11 16:22
    关注

    Unfortunately, I don't think there's going to be an answer that you're happy with. At the end of the day the following must be true:

    Each handler must use the http.Responsewriter and *http.Request to service the request.

    A thing to keep in mind is that shorter and simpler do not always go hand-in-hand. Passing the writer and the response to the functions that need them, while slightly verbose, is exceedingly simple.

    What may make you happiest is to instead push most of the logic actually down into some additional methods that deal in the semantics of the operations rather than the network request layer. Using a GET request to load a record as an example, you might instead structure it as:

    func main() {
        http.DefaultServeMux.HandleFunc("/", getHandler)
    
        if err := http.ListenAndServe(":8080", nil); err != nil {
            panic(err)
        }
    }
    
    func getHandler(w http.ResponseWriter, r *http.Request) {
        // Do stuff with the request, like deserialize
        // Extract the ID
        // Call getLogic
        // return an appropriate error or serialize the response back out
    }
    
    func getLogic(recordID int) (Record, error) {
        // Do actual interesting logic here.
    }
    

    Splitting it up like this is not without a potential cost in simplicity. While it does let you test chunks of your logic without needing to deal with a http.ResponseWriter or http.Request you now have to make a decision where to cut that seam. Doing so consistently might be awkward.

    You could also try to take a different approaches like create a struct per request, put the writer and request on it, and then call the appropriate method, but I wouldn't recommend it:

    func getHandler(w http.ResponseWriter, r *http.Request) {
        SingleRequest{w, r}.Get()
    }
    
    type SingleRequest struct {
        writer  http.ResponseWriter
        request *http.Request
    }
    
    func (s SingleRequest) Get() {
        // Do logic here, but the method still has to access s.writer and s.request
    }
    

    Neither of these approaches offer much in terms of simplicity of brevity. What minor amounts of brevity they do yield is, in my opinion, at the cost of simplicity. The first approach, however, could be reasonable depending on the complexity of a given handler. It is, after all, the extension of the pattern of making smaller functions to break up a larger function.

    As it stands currently, I am unaware of any approach that universally increases simplicity while decreasing code size. Instead, we should focus on why you feel like this is a problem that needs to be solved in the first place. Are you familiar with the httptest package in the standard lib? If testing is your concern it will help you with testing these handlers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作