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 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名