1

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?

OneOfOne
  • 95,033
  • 20
  • 184
  • 185
Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • 1
    Recommended questions+answers to learn how to serve static files: 1. [Include js file in Go template](http://stackoverflow.com/questions/28899675); 2. [With golang webserver where does the root of the website map onto the filesystem](http://stackoverflow.com/questions/28745161); 3.[Why do I need to use http.StripPrefix to access my static files?](http://stackoverflow.com/questions/27945310); 4. [How to serve http partial content with Go?](http://stackoverflow.com/questions/36540610) – icza May 18 '16 at 01:00

1 Answers1

4

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

//edit

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

OneOfOne
  • 95,033
  • 20
  • 184
  • 185