I am currently experimenting with checking if a domain A client can send a domain B cookie to domain B.
Here is the Go code I am using:
package main
import (
"fmt"
"net/http"
"log"
"time"
"encoding/json"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Path: "/test_receive_cookie", Name: "test_cors", Value: "test_cors", Expires: expiration}
http.SetCookie(w, &cookie)
fmt.Fprintf(w, "Success")
}
func receiveCookie(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Cookies())
data := make(map[string]interface{})
for _, cookie := range r.Cookies() {
data[cookie.Name] = cookie.Value
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
func main() {
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/test_receive_cookie", receiveCookie)
err := http.ListenAndServe(":8012", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
To initiate the process, I first access http://localhost:8012/set_cookie
, then I open an HTML file containing JavaScript that uses this library.
this._xhr.get(
"http://localhost:8012/test_receive_cookie",
{ headers: { "Access-Control-Allow-Origin": "*" }},
function(err, resp) {
console.log(resp);
console.log(err);
});
The following outcomes were observed:
- Browser returns
Failed to load http://localhost:8012/test_receive_cookie: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My server prints
[]
fromfmt.Println(r.Cookies())
If I directly access
, I can see the previously set cookie displayed in the browser. However, when I open an HTML page calling that endpoint, the server receives an empty cookie.http://localhost:8012/test_receive_cookie
My question is how can I successfully pass the cookie back to
http://localhost:8012/test_receive_cookie
through client-side code?
Could there be some configuration settings missing in my code?