0

I am working on an application that use image uploading functionality. The application back end is written in Golang where as front end is in Angular4. I am using Gin framework to run http requests in Golang.

Following is the Golang code to upload image:

func UploadFile(c *gin.Context){
    imageData := make(map[string]interface{})
    response := ResponseController{}

    /* ------ Get current date ------ */
    currDate        := time.Now().UTC()
    yearString      := strconv.Itoa(currDate.Year())
    monthString     := strconv.Itoa(int(currDate.Month()))
    dayString       := strconv.Itoa(currDate.Day())

    path := config.UploadBasePath+config.AppFolder+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"

    /* create temp directory if does not exist */
    if _, err := os.Stat(path); os.IsNotExist(err) {
        os.MkdirAll(path, 0755)
    }

    /* read data from form */
    file, err := c.FormFile("file")
    if err != nil {
        response = ResponseController{
            config.FailureCode,
            config.FailureFlag,
            "Error while reading image.",
            nil,
        }
        GetResponse(c, response)
        return
    }
    filePath := path+file.Filename
    if err := c.SaveUploadedFile(file, filePath); err != nil {
        response = ResponseController{
            config.FailureCode,
            config.FailureFlag,
            "Error while uploading image.",
            err,
        }
        GetResponse(c, response)
        return
    }
    uploadUrl := "/"+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"+file.Filename
    imageData["upload_url"] = uploadUrl

    response = ResponseController{
        config.SuccessCode,
        config.SuccessFlag,
        "Image uploaded successfully.",
        imageData,
    }
    GetResponse(c, response)
}

The front end and back end are on same domain having subdomains also. When request generate from front end.

I have passed following headers in Golang code:

c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

Still when I am uploading image, it returns following error in console and image is not getting uploaded:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://SUBDOMAIN.DOMAIN:8080/api/v1/upload. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://[DOMAIN-NAME].com’).

Can anyone guide me what I am missing here. Thanks!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Amandeep kaur
  • 985
  • 3
  • 15
  • 35
  • possible duplicate of https://stackoverflow.com/questions/39507065/enable-cors-in-golang ? – krezus Jan 03 '18 at 12:18
  • 1
    The front end pages must be served using the CORS headers, as far as I know. – Patrick Bucher Jan 03 '18 at 12:30
  • @krezus the link you provided is for Mux. And I am using Gin. – Amandeep kaur Jan 03 '18 at 13:57
  • @PatrickBucher I am providing headers to the request as mentioned above. But it s not working. Do I need to pass something more or else ?? – Amandeep kaur Jan 03 '18 at 13:58
  • 2
    I don't think this is a backend problem. It's the browser blocking your request before it even arrives at the backend. You should look into angular instead. – Vincent van der Weele Jan 03 '18 at 14:01
  • Are you properly responding to `OPTIONS` [preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request)? – Adrian Jan 03 '18 at 14:03
  • @Amandeepkaur It's the Angular user interface that needs to be served with your CORS headers, not the Go application. Your Go backend doesn't care about the same origin policy, it's your browser! – Patrick Bucher Jan 03 '18 at 14:08

1 Answers1

0

Try to set the OPTIONS in your router router.HandleFunc("/", getModulos).Methods("POST", "GET", "OPTIONS")

You can put the CONTENT-TYPE too like this w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

dvaltrick
  • 112
  • 2
  • 7