I am trying to run a basic web app, following a tutorial, using Golang and the routing package Gorilla/mux. The server is running fine but it refuses to find the index.html file regardless of what I put in the browser, always returning a 404.
Here is the code:
main.go
package main
import (
"database/sql"
"fmt"
"net/http"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "0102"
dbname = "bird_encyclopaedia"
)
func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/hello", handler).Methods("GET")
staticFileDirectory := http.Dir("./assets/")
staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))
r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
r.HandleFunc("/bird", getBirdHandler).Methods("GET")
r.HandleFunc("/bird", createBirdHandler).Methods("POST")
return r
}
func main() {
fmt.Println("Starting server dickface...")
connString := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", connString)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
InitStore(&dbStore{db: db})
r := newRouter()
fmt.Println("Serving on port 8080")
http.ListenAndServe(":8080", r)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
The html file is just in the assets/index.html directory, I can supply that if need be but I can't see the problem being in the actual html?
I have trawled through the code many times and cannot see why the server would not be able to find the directory. I have tried localhost/8080/assets, localhost/8080/assets/index.html, localhost/8080, and all other variants.
If I append it with /hello mind it returns the Hello world as seen in main.go And if I append it with /bird it returns "null" instead of 404.