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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测