mp3por
mp3por

Reputation: 1852

Can't read file in GoLang

I am new to GoLang dev and am trying to make a simple web-app. I have been following this tutorial https://www.youtube.com/watch?v=AiRhWG-2nGU.

However I can not even serve the index.html file.

This is my code

func check(e error) {
    if e != nil {
        fmt.Println(e)
        panic(e)
    }
}

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Index functoin")
    indexHTML, err := ioutil.ReadFile("index.html")
    check(err)
    fmt.Println(indexHTML)
    w.Write(indexHTML)
}

and this is the error produced

Index functoin
open index.html: no such file or directory

My tree structure is like so

BasicWebServer/
BasicWebServer/main.go
BasicWebServer/index.html
BasicWebServer/static/
BasicWebServer/static/index.html

All I want is to be able to serve the index.html since it is a AngularJS app which is already running smoothly. I tried with static files like so

router := NewRouter()
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))

but it did not work so I am now trying the most basic approach I could think of.

Please help.

Thank you

Upvotes: 0

Views: 7247

Answers (1)

toqueteos
toqueteos

Reputation: 771

If you want BasicWebServer/main.go to show BasicWebServer/index.html, not the one inside the static folder, then it seems you didn't properly configure the HTTP server.

Here's your code, with package declaration, imports and a main function working as you expected.

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func check(e error) {
    if e != nil {
        fmt.Println(e)
        panic(e)
    }
}

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Index functoin")
    indexHTML, err := ioutil.ReadFile("index.html")
    check(err)
    fmt.Println(indexHTML)
    w.Write(indexHTML)
}

func main() {
    http.HandleFunc("/", Index)

    err := http.ListenAndServe(":8080", nil)
    check(err)
}

Upvotes: 3

Related Questions