Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch-All URL in golang

Tags:

go

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.

like image 383
thotam Avatar asked May 10 '18 22:05

thotam


2 Answers

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

like image 106
Bayta Darell Avatar answered Oct 26 '22 17:10

Bayta Darell


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)
like image 28
guilhebl Avatar answered Oct 26 '22 17:10

guilhebl