ZhangZhihui's Blog  

 

 

 

package main

import (
    "log"
    "net/http"
)

const html = `
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>
  <h1>Simple CORS</h1>
  <div id="output"></div>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      fetch("http://localhost:4000/v1/healthcheck").then(
        function(response) {
          response.text().then(function(text) {
            document.getElementById("output").innerHTML = text;
          });
        },
        function(err) {
          document.getElementById("output").innerHTML = err;
        }
      );
    });
  </script>
</body>

</html>
`

func main() {
    addr := ":9000"

    log.Printf("starting server on %s", addr)

    err := http.ListenAndServe(addr, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte(html))
    }))

    log.Fatal(err)
}

 

 

zzh@ZZHPC:~/zd/Github/greenlight$ go run ./cmd/api
time=2024-11-28T13:48:49.689+08:00 level=INFO msg="database connection pool established"
time=2024-11-28T13:48:49.689+08:00 level=INFO msg="starting server" addr=:4000 env=development

 

zzh@ZZHPC:~/zd/Github/greenlight$ go run ./cmd/examples/cors/simple
2024/11/28 13:47:57 starting server on :9000

 

 

 

 

func (app *application) enableCORS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")

        next.ServeHTTP(w, r)
    })
}

 

In routes.go:

return app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router))))

 

 

 In main.go:

...
type appConfig struct {
    // Fields read from command line
    serverAddress string
    env           string
    cors          struct {
        trustedOrigins []string
    }
...
    flag.Func("cors-trusted-origins", "Trusted CORS origins (space separated)", func(s string) error {
        cfg.cors.trustedOrigins = strings.Fields(s)
        return nil
    })

 

func (app *application) enableCORS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Add the "Vary: Origin" header.
        w.Header().Add("Vary", "Origin")

        origin := r.Header.Get("Origin")

        // Only run this if there's an Origin request header present.
        if origin != "" {
            if slices.Contains(app.config.cors.trustedOrigins, origin) {
                w.Header().Set("Access-Control-Allow-Origin", origin)
            }
        }

        next.ServeHTTP(w, r)
    })
}

 

zzh@ZZHPC:~/zd/Github/greenlight$ go run ./cmd/api -cors-trusted-origins="http://localhost:9000 http://localhost:9001"
time=2024-11-28T15:30:40.308+08:00 level=INFO msg="database connection pool established"
time=2024-11-28T15:30:40.308+08:00 level=INFO msg="starting server" addr=:4000 env=development

 

 

 

package main

import (
    "log"
    "net/http"
)

const html = `
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>
  <h1>Preflight CORS</h1>
  <div id="output"></div>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      fetch("http://localhost:4000/v1/tokens/authentication", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          email: 'alice@example.com',
          password: 'pa55word'
        })
      }).then(
        function(response) {
          response.text().then(function(text) {
            document.getElementById("output").innerHTML = text;
          });
        },
        function(err) {
          document.getElementById("output").innerHTML = err;
        }
      );
    });
  </script>
</body>

</html>
`

func main() {
    addr := ":9000"

    log.Printf("starting server on %s", addr)

    err := http.ListenAndServe(addr, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte(html))
    }))

    log.Fatal(err)
}

 

zzh@ZZHPC:~/zd/Github/greenlight$ go run ./cmd/examples/cors/preflight
2024/11/28 19:02:14 starting server on :9000

 

zzh@ZZHPC:~/zd/Github/greenlight$ go run ./cmd/api -cors-trusted-origins="http://localhost:9000"
time=2024-11-28T19:01:40.013+08:00 level=INFO msg="database connection pool established"
time=2024-11-28T19:01:40.013+08:00 level=INFO msg="starting server" addr=:4000 env=development

 

func (app *application) enableCORS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Add the "Vary: Origin" header.
        w.Header().Add("Vary", "Origin")

        // Add the "Vary: Access-Control-Request-Method" header.
        w.Header().Add("Vary", "Access-Control-Request-Method")

        origin := r.Header.Get("Origin")

        // Only run this if there's an Origin request header present.
        if origin != "" {
            for _, o := range app.config.cors.trustedOrigins {
                if origin == o {
                    w.Header().Set("Access-Control-Allow-Origin", origin)

                    // Check if the request has the HTTP method OPTIONS and contains the 
                    // "Access-Control-Request-Method" header. If it does, we treat it as a 
                    // preflight request.
                    if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
                        w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, PUT, PATCH, DELETE")
                        w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")

                        w.WriteHeader(http.StatusOK)
                        return
                    }

                    break
                }
            }
        }

        next.ServeHTTP(w, r)
    })
}

 

 

 

 

 

posted on 2024-11-28 10:55  ZhangZhihuiAAA  阅读(4)  评论(0编辑  收藏  举报