doudanma9706 2018-05-10 22:46 采纳率: 100%
浏览 107
已采纳

在golang中捕获所有URL

I am planning to rewrite my flask application in golang. I am trying to find a good example for a catch all route in golang similar to my flask application below.

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

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • douzhuan4406 2018-05-10 23:22
    关注

    Use a path ending with "/" to match an entire subtree with 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"}}`)
    }
    

    If the pattern "/es" is not registered, then the mux redirects "/es" to "/es/".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么