我打算用 golang 重写我的 flask 应用程序。我正在尝试为 golang 中的 catch all 路由找到一个很好的例子,类似于下面的 flask 应用程序。

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

任何帮助表示赞赏。

最佳答案

使用以“/”结尾的路径将整个子树与 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"}}`)
}

如果模式“/es”未注册,则复用器将“/es”重定向到“/es/”。

关于go - golang 中的 Catch-All URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50282541/

10-16 07:08