1
1
12rbah2020-09-10 12:34:26
go
12rbah, 2020-09-10 12:34:26

Do I need to run a service with an API and a website on different ports?

Tell me what the problem is, when I launch the api and the site (I mean the visual component), then it is impossible to access the api and returns 404 page not found, if I run it on different ports it works fine.

r := mux.NewRouter()
        //если убрать эти строки то api работает нормально
       //если не убрать то невозможно будет получить доступ к /api/notes
  fs := http.FileServer(http.Dir("public"))
  r.PathPrefix("/").Handler(fs)
        //
  r.HandleFunc("/api/notes", GetNoteHandler).Methods("GET")
  r.HandleFunc("/api/notes", PostNoteHandler).Methods("POST")
  r.HandleFunc("/api/notes/{id}", PutNoteHandler).Methods("PUT")
  r.HandleFunc("/api/notes/{id}", DeleteNoteHandler).Methods("DELETE")
  server := &http.Server{
    Addr:
    ":8080",
    Handler: r,
  }
  log.Println("Listening...")
  err := server.ListenAndServe()
  fmt.Println(err)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Samsonov, 2020-09-10
@12rbah

All requests are processed through FileServerbecause the root level is specified. Do e.g. for files /public, then the api will work. You will also need to remove this prefix withhttp.StripPrefix

fs := http.StripPrefix("/public",  http.FileServer(http.Dir("public")))
r.PathPrefix("/public").Handler(fs)

R
Roman Mirilaczvili, 2020-09-10
@2ord

Different applications (processes) cannot run on the same port.
With such a code, an error will be displayed in the application log and the process will immediately end with an error code.
log.Fatal(server.ListenAndServe())
We also need to remember about CORS.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question