Giter Club home page Giter Club logo

hertz-cors's Introduction

CORS Hertz's middleware

Hertz middleware/handler to enable CORS support.

This repo forks from gin cors and adapt it to Hertz.

Usage

Start using it

Download and install it:

go get github.com/tundrawork/hertz-cors

Import it in your code:

import "github.com/tundrawork/hertz-cors"

Canonical example

package main

import (
	"context"
	"time"

	"github.com/tundrawork/hertz-cors"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
	h := server.Default(
		server.WithHostPorts("127.0.0.1:8080"),
		server.WithHandleMethodNotAllowed(true),  // MUST set to true to enable hertz's handling of OPTIONS requests
	)

	cors := cors.New(cors.Config{
		AllowOrigins:     []string{"https://foo.com"}, // Allowed domains, need to bring schema
		AllowMethods:     []string{"PUT", "PATCH"},    // Allowed request methods
		AllowHeaders:     []string{"Origin"},          // Allowed request headers
		ExposeHeaders:    []string{"Content-Length"},  // Request headers allowed in the upload_file
		AllowCredentials: true,                        // Whether cookies are attached
		AllowOriginFunc: func(origin string) bool { // Custom domain detection with lower priority than AllowOrigins
			return origin == "https://github.com"
		},
		MaxAge: 12 * time.Hour, // Maximum length of upload_file-side cache preflash requests (seconds)
	})

	h.NoMethod(cors)  // handle OPTIONS request by the CORS middleware

	h.GET("/ping", handler.Ping)  // normal route without CORS support

	// add the CORS middleware to a route group
	api := h.Group("/api", cors)  // create a route group with CORS middleware
	api.GET("/challenge", handler.Challenge)  // route with CORS support
	api.POST("/validate", handler.Validate)  // route with CORS support

	// ... or add the CORS middleware to a single route
	h.POST("/upload", append([]app.HandlerFunc{cors}, handler.Upload)...)  // route with CORS support

	h.Spin()
}

Using DefaultConfig as start point

func main() {
  h := server.Default()
  // - No origin allowed by default
  // - GET,POST, PUT, HEAD methods
  // - Credentials share disabled
  // - Preflight requests cached for 12 hours
  config := cors.DefaultConfig()
  config.AllowOrigins = []string{"http://google.com"}
  // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
  // config.AllowAllOrigins = true

  h.Use(cors.New(config))
  h.Spin()
}

note: while Default() allows all origins, DefaultConfig() does not and you will still have to use AllowAllOrigins

Default() allows all origins

func main() {
  h := server.Default()
  // same as
  // config := cors.DefaultConfig()
  // config.AllowAllOrigins = true
  // h.Use(cors.New(config))
  h.Use(cors.Default())
  h.Spin()
}

hertz-cors's People

Contributors

tundrawork avatar skyenought avatar rogerogers avatar dependabot[bot] avatar duslia avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.