Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I enable cors for a particular endpoint? #86

Closed
0xsubi opened this issue Aug 13, 2019 · 3 comments
Closed

How can I enable cors for a particular endpoint? #86

0xsubi opened this issue Aug 13, 2019 · 3 comments

Comments

@0xsubi
Copy link

0xsubi commented Aug 13, 2019

RIght now, I am doing

mux := http.NewServeMux()

mux.HandleFunc("/hello", handleHello)
// Other endpoints

c := cors.New(cors.Options{
		AllowedMethods:         []string{"GET"},
	})

	handler := c.Handler(mux)

	if err := http.ListenAndServe(":8080", handler); err != nil {
		log.Fatal("HTTP server error: ", err)
	}

This enables CORS for all the endpoints, but I want to do so for selective few

@binarypie
Copy link

binarypie commented Aug 15, 2019

You should be able to just wrap your handler function c.Handler(handleHello) instead of wrapping the entire mux.

@masalennon
Copy link

You can write like this for each method:

func YourMethod(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Context-Type", "application/x-www-form-urlencoded")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "DELETE")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  json.NewEncoder(w).Encode(something)
}

@0xsubi
Copy link
Author

0xsubi commented Nov 11, 2019

Thanks for your responses @masalennon @binarypie . Closing this issue

@0xsubi 0xsubi closed this as completed Nov 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants