11

私はGoにかなり慣れていないので、これに関する情報を見つけることができませんでした.おそらく現時点では不可能です.

mux ルートを削除または置換しようとしています (http.NewServeMux、またはゴリラの mux.Router を使用)。私の最終目標は、プログラムを再起動せずにルートまたはルートのセットを有効/無効にできるようにすることです。

おそらくハンドラーごとにこれを達成し、その機能が「無効」の場合は404を返すだけですが、アプリケーションのすべてのルートに実装したいので、これを行うより一般的な方法を見つけたいと思います。

または、無効な URL パターンを追跡し、ミドルウェアを使用してハンドラーの実行を防ぐ方がよいでしょうか?

誰かが少なくとも私を正しい方向に向けることができれば、解決策があると仮定して、解決策のコード例を絶対に投稿します。ありがとう!

4

3 に答える 3

8

組み込みの方法はありませんが、playを実装するのは簡単です。

type HasHandleFunc interface { //this is just so it would work for gorilla and http.ServerMux
    HandleFunc(pattern string, handler func(w http.ResponseWriter, req *http.Request))
}
type Handler struct {
    http.HandlerFunc
    Enabled bool
}
type Handlers map[string]*Handler

func (h Handlers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path
    if handler, ok := h[path]; ok && handler.Enabled {
        handler.ServeHTTP(w, r)
    } else {
        http.Error(w, "Not Found", http.StatusNotFound)
    }
}

func (h Handlers) HandleFunc(mux HasHandleFunc, pattern string, handler http.HandlerFunc) {
    h[pattern] = &Handler{handler, true}
    mux.HandleFunc(pattern, h.ServeHTTP)
}

func main() {
    mux := http.NewServeMux()
    handlers := Handlers{}
    handlers.HandleFunc(mux, "/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("this will show once"))
        handlers["/"].Enabled = false
    })
    http.Handle("/", mux)
    http.ListenAndServe(":9020", nil)
}
于 2014-06-16T21:53:55.750 に答える
0

はい、できます。

http.Handleこれを行う 1 つの方法は、メソッドとのインターフェイスを 実装する構造を持つことServeHTTPです。次に、構造体にゴリラのような別のマルチプレクサを含め、最後にサブルーティングを有効/無効にするアトミック スイッチを設定します。

これは私が意味することの実例です:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
    "sync/atomic"
)

var recording int32

func isRecording() bool {
    return atomic.LoadInt32(&recording) != 0
}

func setRecording(shouldRecord bool) {
    if shouldRecord {
        atomic.StoreInt32(&recording, 1)
    } else {
        atomic.StoreInt32(&recording, 0)
    }
}

type SwitchHandler struct {
    mux http.Handler
}

func (s *SwitchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if isRecording() {
        fmt.Printf("Switch Handler is Recording\n")
        s.mux.ServeHTTP(w, r)
        return
    }

    fmt.Printf("Switch Handler is NOT Recording\n")
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprintf(w, "NOT Recording\n")

}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/success/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Recording\n")
    })

    handler := &SwitchHandler{mux: router}

    setRecording(false)

    http.Handle("/", handler)

    http.ListenAndServe(":8080", nil)
}
于 2014-06-16T21:54:10.087 に答える