Serve html,css,js files under subpath in go mux

804 Views Asked by At

I want to display a compiled angular project under a subpath (eg http://localhost:3000/app/) with go mux

It works as expected without the subpath "app/"

But when I add the subpath with http.StripPrexix("/app/, ..) Handler only index html is found and rendered but without all css, js files..

Test code

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {

    mux := mux.NewRouter()

    fs := http.FileServer(http.Dir("./static/"))

    // Serve static files
    mux.PathPrefix("/app/").Handler(http.StripPrefix("/app/", fs))

    log.Println("Listening...")
    http.ListenAndServe(":3000", mux)
}

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TestProject</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css"></head>
<body>
  <h1>Should work</h1>
  <app-root></app-root>
<script src="runtime.359d5ee4682f20e936e9.js" defer></script><script src="polyfills.bf99d438b005d57b2b31.js" defer></script><script src="main.5dd083c1a27b2a7e410a.js" defer></script></body>
</html>

Working Project Download

This project also includes the static files to serve

https://filehorst.de/d/dubJmmsz

Goal

Serve different projects under different paths

Following on this question

What am I doing wrong?

How to serve the whole project under e.g.: localhost:3000/app/

1

There are 1 best solutions below

4
On BEST ANSWER

The gorilla mux docs mention how to handle Angular SPA applications.

However since you want to base your SPA root to a sub directory, you also need to do the changes in HTML/JS. The base directory should be a variable that will be same as that of prefix of SPA. This is more of a design problem I believe

Otherwise since your rest of the files other than index are resolved at root you need to fallback to "/" for rest of the files & have both configured.

router.PathPrefix("/app").Handler(spa)
router.PathPrefix("/").Handler(spa)

So try like below. I tried your static folder with following:

package main

import (
    "log"
    "net/http"
    "os"
    "path/filepath"
    "time"

    "github.com/gorilla/mux"
)

type spaHandler struct {
    staticPath string
    indexPath  string
}

func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // get the absolute path to prevent directory traversal
    path, err := filepath.Abs(r.URL.Path)
    if err != nil {
        // if we failed to get the absolute path respond with a 400 bad request
        // and stop
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // prepend the path with the path to the static directory
    path = filepath.Join(h.staticPath, path)

    // check whether a file exists at the given path
    _, err = os.Stat(path)
    if os.IsNotExist(err) {
        // file does not exist, serve index.html
        http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
        return
    } else if err != nil {
        // if we got an error (that wasn't that the file doesn't exist) stating the
        // file, return a 500 internal server error and stop
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // otherwise, use http.FileServer to serve the static dir
    http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}

func main() {
    router := mux.NewRouter()

    spa := spaHandler{staticPath: "static", indexPath: "index.html"}
    router.PathPrefix("/app").Handler(spa)

    srv := &http.Server{
        Handler: router,
        Addr:    ":3000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}