我打算用 golang 重写我的烧瓶应用程序。我正在尝试为 golang 中的 catch all 路由找到一个很好的例子,类似于我下面的烧瓶应用程序。
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World! I am running on port ' + str(port)
@app.route('/health')
def health():
return 'OK'
@app.route('/es', defaults={'path': ''})
@app.route('/es/<path:path>')
def es_status(path):
resp = Response(
response='{"version":{"number":"6.0.0"}}',
status=200,
content_type='application/json; charset=utf-8')
return resp
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏。
使用以“/”结尾的路径将整个子树与http.ServeMux匹配。
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// The "/" matches anything not handled elsewhere. If it's not the root
// then report not found.
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
io.WriteString(w, "Hello World!")
})
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "OK")
})
http.HandleFunc("/es/", func(w http.ResponseWRiter, r *http.Request) {
// The path "/es/" matches the tree with prefix "/es/".
log.Printf("es called with path %s", strings.TrimPrefix(r.URL.Path, "/es/"))
w.Header().Set("Content-Type", "application/json; charset=utf-8")
io.WriteString(w, `{"version":{"number":"6.0.0"}}`)
}
Run Code Online (Sandbox Code Playgroud)
如果模式“/es”未注册,则复用器将“/es”重定向到“/es/”。
您可以查看Gorilla Mux,它是 golang 的流行 URL 路由器和调度程序。可以使用 Mux 将示例捕获所有路由配置为:
r := mux.NewRouter()
r.HandleFunc("/specific", specificHandler)
r.PathPrefix("/").Handler(catchAllHandler)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7684 次 |
| 最近记录: |