#do anyone ever faced this issue i have

1 messages · Page 1 of 1 (latest)

warped pond
#

Here is a more complete example of CORS preflight using net/http.


package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/your-endpoint", func(w http.ResponseWriter, r *http.Request) {
        // Set CORS headers
        w.Header().Set("Access-Control-Allow-Origin", "*") // Set this to a specific domain in production
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") // Add other headers if necessary

        // Handle preflight requests
        if r.Method == "OPTIONS" {
            // The preflight request uses OPTIONS method. It's used by the browser to check if the CORS protocol is understood.
            // Just return status code 204 No Content and the necessary headers
            w.WriteHeader(http.StatusNoContent)
            return
        }

        // Continue handling non-preflight requests
        switch r.Method {
        case "GET":
            // Handle GET requests
        case "POST":
            // Handle POST requests
        // Add cases for PUT, DELETE, etc. as necessary
        default:
            // Optionally, handle unsupported methods
            http.Error(w, "Unsupported method", http.StatusMethodNotAllowed)
        }
    })

    http.ListenAndServe(":8080", nil)
}

spiral obsidian
#

Thank you for your insights. Found that it was becasue of the absence of Access-Control-Allow-Headers CORS header, silly me.

Thanks mate