Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Golang web服务器中使用映射处理程序_Go_Webserver - Fatal编程技术网

在Golang web服务器中使用映射处理程序

在Golang web服务器中使用映射处理程序,go,webserver,Go,Webserver,我需要为Golang web服务器中的特定请求定义请求处理程序。我目前的做法如下 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

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

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)
}
这个很好用。然而,我还是刚来戈朗的,所以这可能不是正确的做事方式。我非常感谢任何能够指出是否是实现此结果的更好方法的人

在handleConnection中使用switch语句如何

优点是:

易于理解的代码: 没有apiFunc和gHandlers类型 为了理解路由逻辑,不需要浏览源代码,它都在一个地方 更灵活:您可以使用不同的参数调用函数,并在必要时实现更复杂的路由规则。
我通常倾向于假设查找表比任何类型的运行时条件求值都要快。这似乎支持这一假设。除此之外,我所有的代码都是由脚本发出的,而不是手工编写的,而且生成查找表更干净/更有效。@DroidOS,你提到的线程是2012年的。最新的Go编译器可能产生更快的代码。例如,如果性能非常重要,我建议您对两种不同的方法进行基准测试。@DroidOS,如果代码是自动生成的,除了Go编译器之外没有人看它,那么我认为它是否是惯用的并不重要。尽可能提高效率。以stringer输出为例,我刚才顺便提到了可能的速度问题。这里更重要的问题是,发出查找表比构建冗长的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
}