You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Flask应用迁移至Golang,求Catch-All路由实现示例

Got it, let's convert your Flask app to Go with equivalent routing behavior. I'll show you two approaches: one using Go's built-in net/http package (no external dependencies) and another with the popular gorilla/mux router for cleaner, more flexible route definitions.

Using Go's Standard net/http Package

This lightweight implementation matches your Flask app's functionality exactly:

package main

import (
	"fmt"
	"net/http"
)

// Define your server port (mirrors the port variable in your Flask code)
const port = 8080

func helloHandler(w http.ResponseWriter, r *http.Request) {
	// Ensure we only respond to the exact root path (avoids catching unintended routes)
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	w.Write([]byte(fmt.Sprintf("Hello World! I am running on port %d", port)))
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	// Only handle the exact /health path
	if r.URL.Path != "/health" {
		http.NotFound(w, r)
		return
	}
	w.Write([]byte("OK"))
}

func esHandler(w http.ResponseWriter, r *http.Request) {
	// Set the correct JSON content type and 200 status code
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	// Return the hardcoded JSON response (matches your Flask Response object)
	w.Write([]byte(`{"version":{"number":"6.0.0"}}`))
}

func main() {
	// Register route handlers
	http.HandleFunc("/", helloHandler)
	http.HandleFunc("/health", healthHandler)
	// Handle both the exact /es path and any subpath under /es/ (mirrors your Flask dual routes)
	http.HandleFunc("/es", esHandler)
	http.HandleFunc("/es/", esHandler)

	// Start the server
	fmt.Printf("Server starting on port %d...\n", port)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
		fmt.Printf("Server failed to start: %v\n", err)
	}
}

Key Details:

  • The root and /health handlers include path checks because the standard library's / handler acts as a fallback by default—this ensures we don't accidentally respond to unrelated paths.
  • We register two handlers for /es to cover both the exact path and any subpaths, just like your Flask setup with defaults={'path': ''} and <path:path>.

Using gorilla/mux (Cleaner Routing)

If you want more concise route definitions (especially for catch-all paths), gorilla/mux is a great choice. First install it with go get github.com/gorilla/mux:

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const port = 8080

func helloHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(fmt.Sprintf("Hello World! I am running on port %d", port)))
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("OK"))
}

func esHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"version":{"number":"6.0.0"}}`))
}

func main() {
	// Initialize the mux router
	r := mux.NewRouter()

	// Register precise routes
	r.HandleFunc("/", helloHandler)
	r.HandleFunc("/health", healthHandler)
	// PathPrefix automatically matches /es AND any path starting with /es/ (one line instead of two!)
	r.PathPrefix("/es").HandlerFunc(esHandler)

	// Start the server
	fmt.Printf("Server starting on port %d...\n", port)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), r); err != nil {
		fmt.Printf("Server failed to start: %v\n", err)
	}
}

Key Details:

  • PathPrefix("/es") handles both the exact /es path and all subpaths under /es/ in one line, eliminating the need for duplicate handler registrations.
  • gorilla/mux offers extra features like route variables, regex matching, and middleware if you need to expand your app later.

Both implementations will behave exactly like your Flask app—test them by hitting /, /health, /es, and /es/any/random/path to confirm!

内容的提问来源于stack exchange,提问作者thotam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:11:16