duanfan8699 2018-07-15 22:40
浏览 796

如何在GoLang中覆盖组合的struct方法

I want to make a controller struct in GoLang that has a ServeHTTP method which calls its own methods (which responds with a 405 status code) based on that of the HTTP request. New controllers should be able to inherit ServeHTTP while also being able to override methods like Get(w http.ResponseWriter, r *http.Request) and have the new ones being triggered by ServeHTTP. Then, controllers can be assigned as route handlers with the http module. I know how to do this in Java (have a controller superclass with all basic methods), but the method overriding part fails in Go. Here is my code:

package main

import "net/http"

type Controller struct { }

func notAllowed(w http.ResponseWriter){
    w.WriteHeader(http.StatusMethodNotAllowed)
    w.Write([]byte("405- Method Not Allowed"))
}
func(c Controller)  Get(w http.ResponseWriter, r *http.Request){
    notAllowed(w)
}
func(c Controller)  Post(w http.ResponseWriter, r *http.Request){
    notAllowed(w)   
}
func(c Controller)  Put(w http.ResponseWriter, r *http.Request){
    notAllowed(w)   
}
func(c Controller)  Patch(w http.ResponseWriter, r *http.Request){
    notAllowed(w)   
}
func(c Controller)  Delete(w http.ResponseWriter, r *http.Request){
    notAllowed(w)   
}
func(c Controller)  ServeHTTP(w http.ResponseWriter, r *http.Request){
    switch r.Method {
        case "GET":
            c.Get(w, r)
        case "POST":
            c.Post(w, r)
        case "PUT":
            c.Put(w, r)
        case "PATCH":
            c.Patch(w, r)
        case "DELETE":
            c.Delete(w, r)
    }
}
type Index struct {
  Controller  
}
func(I Index) Get(w http.ResponseWriter, r http.Request){
  w.Write([]byte("hello"))
}
func main(){
  http.Handle("/", Index{})
  http.ListenAndServe(":8080", nil)
}
  • 写回答

1条回答 默认 最新

  • dptdb84606 2018-07-16 02:41
    关注

    Thank you to @mkopriva; here is the answer he put in the comments: https://play.golang.org/p/1-LEOjTo0AX

    Apparently methods will only be overriden with reverse composition.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧