duanmeng1858 2016-05-17 23:01
浏览 36
已采纳

在运行中,手动调用http.FileServer和/或什么是http处理程序

I'm an experienced programmer, but new to go. Apologies in advance if this is an obvious question or well tread path. I'm still getting my bearings in the language and its semantics.

I'm trying to create a web server in go that

  1. Examines the HTTP request
  2. Based on the results of the request, serves a specific static folder

i.e., something where the simplified pseudo code looks like

import (
    "io"
    "net/http"
    "fmt"
    "strings"
    "encoding/base64"
)

func examineRequest(request *http.Request) {
    //looks at request header
    if(request headers have one thing){
        return "foo"
    }
    return "bar"
}

func processRequest(responseWriter http.ResponseWriter, request *http.Request) {
    folderToServe = examineRequest(request);
    if folderToServe == "bar" {
        //serve static files from the ./static/bar folder

        //go freaks out if I try these
        //http.Handle("/", http.FileServer(http.Dir("./static/bar")))      
        //http.FileServer(http.Dir("./static/bar")()

    }
    else if folderToServer == "foo" {
        //serve static files from the ./static/foo folder

        //go freaks out if I try these
        //http.Handle("/", http.FileServer(http.Dir("./static/foo")))      
        //http.FileServer(http.Dir("./static/foo")()
    }
}

func main(){
    http.HandleFunc("/", processRequest)  
    //http.Handle("/", http.FileServer(http.Dir("./static")))      
}

Experienced go programmers may have already spotted the problem. I'm performing my examination in processRequest, and because of that, its too late to to call Handle -- however, you can't register more than one handle for the same path in go, and nested handle calls freak go out.

I though the handler might be similar to an anonymous function in other languages and tried call it -- but go did like that either.

So -- is there a way to manually invoke the handler returned from the call to http.FileServer(http.Dir("./static"))?

Is that even the right question to be asking here?

What exactly is a handler in the context of the http module?

  • 写回答

1条回答 默认 最新

  • dongzhan2029 2016-05-17 23:15
    关注

    Use http.FileServer(http.Dir("./static/foo")).ServeHTTP(w, req).

    //edit

    http.FileServer returns an http.Handler which in turn provides the ServerHTTP method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码