github.com/Jeffail/benthos/v3@v3.65.0/internal/http/docs/cors.go (about)

     1  package docs
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  
     7  	"github.com/Jeffail/benthos/v3/internal/docs"
     8  	"github.com/gorilla/handlers"
     9  )
    10  
    11  // ServerCORS contains configuration for allowing CORS headers.
    12  type ServerCORS struct {
    13  	Enabled        bool     `json:"enabled" yaml:"enabled"`
    14  	AllowedOrigins []string `json:"allowed_origins" yaml:"allowed_origins"`
    15  }
    16  
    17  // NewServerCORS returns a new server CORS config with default fields.
    18  func NewServerCORS() ServerCORS {
    19  	return ServerCORS{
    20  		Enabled:        false,
    21  		AllowedOrigins: []string{},
    22  	}
    23  }
    24  
    25  // WrapHandler wraps a provided HTTP handler with middleware that enables CORS
    26  // requests (when configured).
    27  func (conf ServerCORS) WrapHandler(handler http.Handler) (http.Handler, error) {
    28  	if !conf.Enabled {
    29  		return handler, nil
    30  	}
    31  	if len(conf.AllowedOrigins) == 0 {
    32  		return nil, errors.New("must specify at least one allowed origin")
    33  	}
    34  	return handlers.CORS(
    35  		handlers.AllowedOrigins(conf.AllowedOrigins),
    36  		handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}),
    37  	)(handler), nil
    38  }
    39  
    40  // ServerCORSFieldSpec returns a field spec for an http server CORS component.
    41  func ServerCORSFieldSpec() docs.FieldSpec {
    42  	return docs.FieldAdvanced("cors", "Adds Cross-Origin Resource Sharing headers.").WithChildren(
    43  		docs.FieldBool("enabled", "Whether to allow CORS requests.").HasDefault(false),
    44  		docs.FieldString("allowed_origins", "An explicit list of origins that are allowed for CORS requests.").Array().HasDefault([]string{}),
    45  	).AtVersion("3.63.0")
    46  }