Sammy Roberts Sammy Roberts - 4 months ago 10
HTML Question

Trouble finding assets on my HTML, serving from a Go web server

I am editing some tutorial code I found online, and wanted to add a front end. I got my router spitting out my html no problem, but the html cannot find my static files.
here is my main function

func main() {
router := NewRouter()
cssHandler := http.FileServer(http.Dir("./css/"))
imagesHandler := http.FileServer(http.Dir("./images/"))
scriptHandler := http.FileServer(http.Dir("./scripts/"))

http.Handle("/scripts/", http.StripPrefix("/scripts/", scriptHandler))
http.Handle("/css/", http.StripPrefix("/css/", cssHandler))
http.Handle("/images/", http.StripPrefix("/images/", imagesHandler))
log.Fatal(http.ListenAndServe(":8080", router))


}

here is my index

<!DOCTYPE html>
<html>
<head>
<title>Go Do IT</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="./scripts/app.js"></script>
<script type="text/javascript" src="./scripts/toDoCtrl.js"></script>
</head>
<body ng-app="app">
<div ng-controller="toDoCtrl as ctrl">
<div ng-repeat ="todo in ctrl.todos">
{{todo}}
</div>
</div>
</body>




if you want to see all the code, here is a repo i am working on https://github.com/kekeoki/go-do-it
I have tried putting things in a grouped static folder, and most recently I moved the scripts folder to the base directory. If you have any good tutorial links, please let me know, everything I have found so far has not helped.
Thanks

Answer

Finally got it working, YOU MUST HAVE THE ./ IN FRONT OR IT WONT WORK.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func ServeStatic(router *mux.Router, staticDirectory string) {
    staticPaths := map[string]string{
        "styles":           staticDirectory + "/styles/",
        "bower_components": staticDirectory + "/bower_components/",
        "images":           staticDirectory + "/images/",
        "scripts":          staticDirectory + "/scripts/",
    }
    fmt.Println(staticPaths)

    for pathName, pathValue := range staticPaths {
        pathPrefix := "/" + pathName + "/"
        router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
            http.FileServer(http.Dir(pathValue))))
        fmt.Println(pathValue)
    }
}
func main() {
    router := NewRouter()

    staticDirectory := "./static"
    ServeStatic(router, staticDirectory)

    log.Fatal(http.ListenAndServe(":8080", router))
}

my scripts are in ./static/scripts/ I.E. ./static/scripts/app.js TLDR treat each asset route as a route on your router, not a space on your file system