Skip to content

acoshift/cors

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 

Repository files navigation

cors

Go Report Card GoDoc

CORS middleware for Golang net/http

Example

package main

import (
	"fmt"
	"net/http"

	"github.com/acoshift/cors"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "OK")
}

func main() {
	h := cors.New(cors.Config{
		AllowOrigins:     []string{"localhost:8080"},
		AllowMethods:     []string{http.MethodGet, http.MethodPost},
		AllowHeaders:     []string{"Authorization"},
		AllowCredentials: true,
	})(http.HandlerFunc(handler))
	http.ListenAndServe(":8080", h)
}

or use with middleware

package main

import (
	"fmt"
	"net/http"

	"github.com/acoshift/cors"
	"github.com/acoshift/middleware"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "OK")
}

func main() {
	h := middleware.Chain(
		cors.New(cors.Config{
			AllowOrigins:     []string{"localhost:8080"},
			AllowMethods:     []string{http.MethodGet, http.MethodPost},
			AllowHeaders:     []string{"Authorization"},
			AllowCredentials: true,
		}),
	)(http.HandlerFunc(handler))
	http.ListenAndServe(":8080", h)
}