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) }) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-11-28 SQLC - Installation
2023-11-28 SQLC - Why SQLC?