7

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 Answers 2

15

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/".

Sign up to request clarification or add additional context in comments.

Comments

5

You can take a look on Gorilla Mux which is a popular URL router and dispatcher for golang. A sample catch all route could be configured using Mux as:

r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) 

1 Comment

This does not work for me. Any requests that aren't "/" just 404.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.