2014-11-19 1 views
1

나는 아래의 코드로 서버를 실행하고 있습니다 :Golang의 Negroni입니다 및 http.NewServeMux() 문제

// Assuming there is no import error 
    mux := http.NewServeMux() 
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 
    http.Error(w, "File not found", http.StatusNotFound) 
    }) 

    n := negroni.Classic() 
    n.Use(negroni.HandlerFunc(bodmas.sum(4,5))) 
    n.UseHandler(mux) 
    n.Run(":4000") 

그것은 완벽하게 잘 작동합니다.

그러나 bodmas.sum을 다른 http handler으로 감 으면 항상 "파일을 찾을 수 없습니다."라는 메시지가 나타납니다. 흐름이이 경로로 이동하지 않습니다.

mux := http.NewServeMux() 
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 
    http.Error(w, "File not found", http.StatusNotFound) 
    }) 

    n := negroni.Classic() 
    n.Use(negroni.HandlerFunc(wrapper.RateLimit(bodmas.sum(4,5),10))) 
    n.UseHandler(mux) 
    n.Run(":" + cfg.Server.Port) 
} 

wrapper.RateLimit은 다음과 같이 정의됩니다. 별도로 테스트 할 때 예상대로 작동합니다.

func RateLimit(h resized.HandlerFunc, rate int) (resized.HandlerFunc) { 
    : 
    : 
    // logic here 

    rl, _ := ratelimit.NewRateLimiter(rate) 

    return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc){ 
     if rl.Limit(){ 
      http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout) 
     } else { 
      next(w, r) 
     } 
    } 
} 

오류가 없습니다. 이 동작에 대한 제안 사항이 있습니까? 작동 원리

답변

2

이 코드의 문제점은 무엇인지 확실하지 않지만, negorni 방법이 아닌 것으로 보입니다. negroni은 핸들러를 다른 http.Handlerfunc으로 감싸는 경우 예상대로 작동하지 않을 수 있습니다. 따라서 코드를 수정하고 middleware으로 작업을 완료했습니다.

내 현재 코드는 다음과 같은 :

  mux := http.NewServeMux() 
      mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 
      http.Error(w, "File not found", http.StatusNotFound) 
      }) 

      n := negroni.Classic() 
      n.Use(wrapper.Ratelimit(10)) 
      n.Use(negroni.HandlerFunc(bodmas.sum(4,5))) 
      n.UseHandler(mux) 
      n.Run(":4000") 
    } 

wrapper.go가 있습니다

type RatelimitStruct struct { 
      rate int 
    } 

    // A struct that has a ServeHTTP method 
    func Ratelimit(rate int) *RatelimitStruct{ 
     return &RatelimitStruct{rate} 
    } 

    func (r *RatelimitStruct) ServeHTTP(w http.ResponseWriter, req *http.Request, next  http.HandlerFunc){ 
     rl, _ := ratelimit.NewRateLimiter(r.rate) 

     if rl.Limit(){ 
      http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout) 
     } 

else { 
     next(w, req) 
    } 
} 

가 누군가를 도움이되기를 바랍니다.