go - 在 Golang Web 服务器中使用映射处理程序

标签 go webserver

我需要为我的 Golang 网络服务器中的特定请求定义请求处理程序。我目前的做法如下

package main

import "net/http"

type apiFunc func(rg string, w http.ResponseWriter, r *http.Request)

func h1(rg string, w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Bonjour"))
}

func h2(rg string, w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Guten Tag!"))
}

func h3(rg string, w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Good Morning!"))
}

type gHandlers map[string]apiFunc

var handlers gHandlers

func handleConnection(w http.ResponseWriter, r *http.Request) {
    hh := r.URL.Query().Get("handler")
    handlers[hh]("rg", w, r)
}

func main() {
    handlers = make(map[string]apiFunc, 3)
    handlers["h1"] = h1
    handlers["h2"] = h2
    handlers["h3"] = h3
    http.HandleFunc("/", handleConnection)
    http.ListenAndServe(":8080", nil)
}

这很好用。然而,我仍然是 Golang 的新手,所以它可能不是“正确”的做事方式。对于任何能够指出是否是实现此结果的更好方法的人,我将非常感激

最佳答案

handleConnection 中使用 switch 语句如何?

switch hh {
case "h1":
    h1("rg", w, r)
case "h2":
    h2("rg", w, r)
case "h3":
    h3("rg", w, r)
default:
    // return HTTP 400 here
}

优点是:

  • 更易于理解的代码:
    • 没有 apiFuncgHandlers 类型
    • 无需浏览源代码即可了解路由逻辑,一切尽在一处
  • 更灵活:您可以调用具有不同参数的函数,并在必要时实现更复杂的路由规则。

关于go - 在 Golang Web 服务器中使用映射处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31333059/

相关文章:

java - 当我使用内部服务器时,如何解决 IOException 问题。 (Java/安卓)

python - 用 uwsgi 替换 nginx

c++ - panic : Failed to load dbcapi. dll:

go - 将未知长度的 slice 中的值分配给 Go 中的结构体?

python - cherrypy 是如何工作的?当并发率低时,与 Tornado 相比,它可以很好地处理请求

webserver - 我的设备在 .NET Micro Framework 上的 Web 服务器

python - pymysql.err.OperationalError : (1045, "Access denied for user ' MYID' @'localhost' (using password: NO)")

go - 在 Golang 中绕过 http_proxy

sql-server - 如何使用 Windows 身份验证连接到 SQL Server?

go - 你如何让一个函数接受多种类型?