Last active
January 4, 2023 15:20
-
-
Save adityathebe/f5905b9e28bbc78ba2abbd69e88a5c0d to your computer and use it in GitHub Desktop.
Sample code for my article - https://www.adityathebe.com/follow-redirection-on-cross-origin-requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
func handleNoCors(w http.ResponseWriter, req *http.Request) { | |
fmt.Println("Request received. Referer:", req.Header.Get("Referer")) | |
w.Write([]byte("Hello world!")) | |
} | |
func handleCors(w http.ResponseWriter, req *http.Request) { | |
fmt.Println("[/cors] Request received. Referer:", req.Header.Get("Referer")) | |
w.Header().Set("Content-Type", "application/json") | |
w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com") | |
w.Write([]byte("{\"msg\":\"success\"}")) | |
} | |
func handleCorsRedirection(w http.ResponseWriter, req *http.Request) { | |
fmt.Println("[/cors-redirect] Request received. Referer:", req.Header.Get("Referer")) | |
w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com") | |
w.Header().Set("Location", "/cors") | |
w.WriteHeader(http.StatusFound) | |
} | |
func handleNoCorsRedirection(w http.ResponseWriter, req *http.Request) { | |
fmt.Println("[/no-cors-redirect] Request received. Referer:", req.Header.Get("Referer")) | |
w.Header().Set("Location", "/cors") | |
w.WriteHeader(http.StatusFound) | |
} | |
func main() { | |
http.HandleFunc("/cors", handleCors) | |
http.HandleFunc("/nocors", handleNoCors) | |
http.HandleFunc("/cors-redirect", handleCorsRedirection) | |
http.HandleFunc("/no-cors-redirect", handleNoCorsRedirection) | |
http.ListenAndServe(":3000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment