I solved with the following:

package main


import (
 "log"
 "net/http"


 "github.com/gorilla/mux"
)


func corsMiddleware(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 log.Println("Executing middleware", r.Method)


 if r.Method == "OPTIONS" {
 w.Header().Set("Access-Control-Allow-Origin", "*")
 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, 
DELETE, OPTIONS")
 w.Header().Set("Access-Control-Allow-Headers:", "Origin, Content-Type, 
X-Auth-Token, Authorization")
 w.Header().Set("Content-Type", "application/json")
 return
 }


 next.ServeHTTP(w, r)
 log.Println("Executing middleware again")
 })
}


func adminLogin(w http.ResponseWriter, r *http.Request) {
 log.Println("Executing adminLogin")
 w.Write([]byte("adminLogin"))
}


func allClinics(w http.ResponseWriter, r *http.Request) {
 log.Println("Executing allClinics")
 w.Write([]byte("allClinics"))
}


func main() {
 r := mux.NewRouter()
 r.HandleFunc("/adminlogin", adminLogin).Methods("POST")
 r.HandleFunc("/clinics", allClinics).Methods("GET")
 log.Fatal(http.ListenAndServe(":3000", corsMiddleware(r)))
}


// curl localhost:3000/clinics -v
// curl -X POST localhost:3000/adminlogin -v




On Sunday, June 4, 2017 at 7:54:17 AM UTC-7, Oren wrote:
>
> Any ideas why I get '403: forbidden' when making CORS request to my web 
> service? 
> https://github.com/oren/doc-api/blob/dc332507e3a9c5f36a2de6430ec6bf811ffcbd4e/cmd/web/server.go#L90
>
> I am using gorilla mux:
> ```
> corsObj := handlers.AllowedOrigins([]string{"*"})
> log.Fatal(http.ListenAndServe(":3000", handlers.CORS(corsObj)(r)))
> ```
>
> Here are more details from the chrome dev tools console:
>
> General:
> Request URL:http://localhost:3000/adminlogin
> Request Method:OPTIONS
> Status Code:403 Forbidden
> Remote Address:[::1]:3000
> Referrer Policy:no-referrer-when-downgrade
>
> Request Headers:
> Accept:*/*
> Accept-Encoding:gzip, deflate, sdch, br
> Accept-Language:en-US,en;q=0.8
> Access-Control-Request-Headers:content-type
> Access-Control-Request-Method:POST
> Connection:keep-alive
> DNT:1
> Host:localhost:3000
> Origin:http://localhost:8080
> Referer:http://localhost:8080/login
>
> Thanks!
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to