One-Winged_Eagle
One-Winged_Eagle

Reputation: 61

Serving files with Echo

I'm trying to serve multiple files with Echo, but it doesn't work every time. The api code looks like this:

package main

import (
    "github.com/labstack/echo"

    "net/http"
)

func main() {
    e := echo.New();

    e.GET("/", home);

    e.File("/data1", "assets/data1.csv");

    e.File("/data2", "assets/data2.csv");

    e.Logger.Fatal(e.Start(":4243"));
}

func home(c echo.Context) error {
  return c.String(http.StatusOK, "Are you lost?");
}

To be precise, it does work for the very first file fetching, but then keeps failing for any subsequent calls (be them file fetching or more "classic" calls). The error message is a tad different for each browser:

In Chrome:

SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Bearer {the_entire_content_of_the_first_fetched_file}' is not a valid HTTP header field value.

In Firefox:

SyntaxError: An invalid or illegal string was specified

In Edge, simply:

SyntaxError

Tried activating CORS, nothing changed.

Looks to work pretty well with Postman. Maybe it's a problem with how I do fetch my data in my application?

If you need perhaps a bit more information, this thread is directly related to my previous one (Vuejs with axios request in vuex store: can't make more than one request, why?), but I didn't want to mix them up, as I don't know yet if I'm mistaken in my Vue code or my Echo one...

Upvotes: 0

Views: 11439

Answers (3)

One-Winged_Eagle
One-Winged_Eagle

Reputation: 61

Welp, seems it was my application's fault all along! My Echo api seems fine... for now!

If someone has the same problem, perhaps this Vuejs with axios request in vuex store: can't make more than one request, why? will help.

Upvotes: -1

Rahmat Aligos
Rahmat Aligos

Reputation: 1294

Just Add default CORS Middleware, i just test and it's work fine even i using difference domain. import this package from echo framework: "github.com/labstack/echo/middleware" and Add this default CORS config befor your route:

e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
}))

Upvotes: 0

jeevatkm
jeevatkm

Reputation: 4791

If you would like to delivery files from certain directory. You can do following ways:

e.Use(middleware.Static("/path/to/directory"))

OR

fs := http.FileServer(http.Dir("/path/to/directory"))
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/assets/", fs)))

Upvotes: 6

Related Questions