add cors headers to a http server with a specific origin and methods in go

To add CORS headers to an HTTP server in Go, we can use the cors middleware package provided by the handlers package.

Here is an example of how to use it:

main.go
package main

import (
    "net/http"

    "github.com/gorilla/handlers"
)

func main() {
    router := http.NewServeMux()

    // Add your HTTP routes here...

    // Create the CORS middleware with allowed origins and methods
    cors := handlers.CORS(
        handlers.AllowedOrigins([]string{"https://my-client.com"}),
        handlers.AllowedMethods([]string{"GET", "POST"}),
    )

    // Wrap your HTTP server with the CORS middleware
    http.ListenAndServe(":8080", cors(router))
}
491 chars
23 lines

In this example, we create an HTTP server using the http package's NewServeMux() function. We then add our HTTP routes to the router.

Next, we create the CORS middleware using the handlers.CORS() function. We specify the allowed origins as an array of strings that contain the hostnames of our client application. We also specify the allowed methods as an array of strings that contain the HTTP request methods that we want to allow.

Finally, we wrap our HTTP server with the CORS middleware using the http.ListenAndServe() function. The first argument is the TCP address to listen on, and the second argument is the wrapped http.Handler returned by the cors(router) function call.

With this setup, any HTTP requests made to our server from the https://my-client.com origin will include the appropriate CORS headers in their response. Other origins will receive an error response instead.

gistlibby LogSnag