2017-09-19 7 views
0

라우팅을 처리 할 때 다양한 미들웨어 기능을 지원하는 Go 웹 애플리케이션을 구축 중입니다. 가능한 한 많이 net/http을 고수하려고하고 있는데, negroni과 같은 미들웨어 라이브러리를 사용하지 않고 어떻게이 작업을 수행 할 수 있는지 궁금합니다.Slest의 네스트 기능

필자가하고자하는 것은 미들웨어 기능을 제공하는 것입니다. 하나는 로깅, 하나는 유효한 JWT를 확인한 다음 마지막으로 요청을 처리하는 것입니다.

// Route .. 
type Route struct { 
    Method  string 
    Path  string 
    Middleware []negroni.Handler 
    Handler http.HandlerFunc 
} 

다음과 같은 경로를 정의 : 나는 다음과 같은 구조체를 정의하여 비교적 간단하게 -Negroni입니다 함께 할 수 있어요

var commonRoutes = []Route{ 
    { 
     Method:  "GET", 
     Path:  "/info", 
     Middleware: []negroni.Handler{negroni.HandlerFunc(middleware.CheckCache), negroni.HandlerFunc(middleware.Authenticated), negroni.NewLogger()}, 
     Handler: handlers.APIInfo, 
    }, 
} 

마지막으로 내 서버를 부팅 할 때, I 경로 목록을 가져 와서 다음과 같이 등록하십시오.

for _, r := range routes { 

    handler := append(r.Middleware, negroni.Wrap(r.Handler)) 

    router.Handle(r.Path, negroni.New(handler...)).Methods(r.Method) 
} 

그리고 완벽하게 작동합니다.

내가 같이 단지 표준 net/http 서명 및 미들웨어 핸들러를 정의하는 방법으로이 작업을 수행 할 수있을 어떻게 어떤 생각 :

http.Handle("/", middlewareOne(middlewareTwo(finalHandler))) 

당신 :

답변

1
func Auth(n http.Handler) http.Handler { 
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 
     log.Printf("Start") 
     n.ServeHTTP(w, r) 
     log.Printf("End") 
    }) 
} 

func processReq(w http.ResponseWriter, r *http.Request) { 
    w.Write([]byte("Success")) 
} 


func main() { 
    handler := http.HandlerFunc(processReq) 

    http.Handle("/",Auth(handler)) 
    http.ListenAndServe(":8000", nil) 
} 

할 수있는 감사 http.handler를 사용하여 수행하십시오.

0

Simple.

// So I don't have to type it over and over... 
type HTTPHandler func(w http.ResponseWriter, r *http.Request) 

func Handler1(next HTTPHandler) HTTPHandler { 
    return func(w http.ResponseWriter, r *http.Request){ 
     // Do stuff 

     if next != nil { 
      next(w, r) 
     } 
    } 
} 

// Handler2 ... HandlerN defined in the same basic way. 

// Chaining: 
http.Handle("/", Handler1(Handler2(nil))) 

각 처리기는 다음 처리기를 사용하여 원하는대로 처리하고 다음 처리기를 호출하는 클로저를 반환합니다. 이러한 것들을 많이 필요로한다면 이것과 비슷한 도우미를 쓰는 것이 좋습니다.

func MakeHandler(worker, next HTTPHandler) HTTPHandler { 
    return func(w http.ResponseWriter, r *http.Request){ 
     // Maybe have to worker return an error and do standard error 
     // handling here? Could simplify your code some depending on 
     // what you are doing. 
     worker(w, r) 

     if next != nil { 
      next(w, r) 
     } 
    } 
}