Created
June 28, 2017 02:41
-
-
Save lisp-ceo/77b180fbbfb7fac6a0078e96f25b69cc to your computer and use it in GitHub Desktop.
Testing a static file server deployment in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Simple static file server in go | |
// Usage: | |
// -p="6969": port to serve on | |
// -d="./static": the directory of static files to host | |
import ( | |
"flag" | |
"log" | |
"net/http" | |
"sync" | |
) | |
var ( | |
wg sync.WaitGroup | |
port = flag.String("p", "6969", "Port to serve on") | |
directory = flag.String("d", "./static", "Directory of static files to host") | |
) | |
func main() { | |
wg.Add(1) | |
_ = StartServer() | |
// Server runs forever | |
wg.Wait() | |
} | |
func StartServer() *http.Server { | |
flag.Parse() | |
srv := &http.Server{Addr: ":" + *port} | |
http.Handle("/", http.FileServer(http.Dir(*directory))) | |
go func() { | |
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port) | |
if err := srv.ListenAndServe(); err != nil { | |
log.Printf("Httpserver: ListenAndServe() error: %s", err) | |
} | |
}() | |
return srv | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"testing" | |
) | |
func setupServer(t *testing.T) func(*testing.T) { | |
srv := StartServer() | |
return func(*testing.T) { | |
srv.Shutdown(nil) | |
} | |
} | |
func TestRouting(t *testing.T) { | |
tearDown := setupServer(t) | |
defer tearDown(t) | |
routes := []struct { | |
uri string | |
respCode int | |
}{ | |
{"http://0.0.0.0:6968/", 200}, | |
{"http://0.0.0.0:6968/index.html", 200}, | |
{"http://0.0.0.0:6968/activated.html", 200}, | |
{"http://0.0.0.0:6968/doesnt_exist.html", 404}, | |
} | |
for _, route := range routes { | |
res, err := http.Get(route.uri) | |
if err != nil { | |
t.Errorf("Failed to get URI: %s", err) // TODO IS this a method? | |
} | |
if route.respCode != res.StatusCode { | |
t.Errorf("Expected %d, received %d", route.respCode, res.StatusCode) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment