Problem:
I am having trouble finding the answer to a question, which there is a BIG possibility I do not know how to ask.
I am having problem with Go Server. I do not have any big knowledge of go programming but I did make a server with it. This server will display a JSON file which will then be pulled my other HTML file which is now irrelevant. This works. My problem is the path to the server.
Code
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type Event struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
Summary string `json:"summary"`
Organizer string `json:"organizer"`
MeetURL string `json:"meet_url"`
}
type EventSlice struct {
Events []Event `json:"events"`
}
func loadEvents(filename string) (EventSlice, error) {
// Open events file.
file, err := os.Open(filename)
if err != nil {
return EventSlice{}, err
}
var list EventSlice
// Parse events from json file to events slice.
err = json.NewDecoder(file).Decode(&list)
if err != nil {
fmt.Println("Displays", err)
return EventSlice{}, err
}
return list, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
events, err := loadEvents("json.json")
if err != nil {
fmt.Fprintln(w, err)
}
// Reduntant step in real life
err = json.NewEncoder(w).Encode(events)
if err != nil {
fmt.Fprintln(w, err)
}
}
func handler_over(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is my server. Hello.")
}
func main() {
http.HandleFunc("/", handler_over)
http.HandleFunc("/events", handler)
http.ListenAndServe(":8080", nil)
}
And if I go run the server and then on this url change the path to example: http://0.0.0.0:8080/otherpath, it will still display function for handler_over. Which will display a string: This is my server.Hello
.
What would I have to do, so when you change the URL to unknown path (which is not a path) that it will display an Error like 404 Page not found. In meaning, that only 2 paths will be recognisable on the server: "/" path and "/events" path.
Note This question has already probably been asked before, but I do not know how to ask the question. Any help or redirections to the answers would be gladly appreciated.
func handler_over(w http.ResponseWriter, r *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if r.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "This is my server. Hello.")
}