CORS 示例

服务端

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/labstack/echo"
  5. "github.com/labstack/echo/middleware"
  6. )
  7. var (
  8. users = []string{"Joe", "Veer", "Zion"}
  9. )
  10. func getUsers(c echo.Context) error {
  11. return c.JSON(http.StatusOK, users)
  12. }
  13. func main() {
  14. e := echo.New()
  15. e.Use(middleware.Logger())
  16. e.Use(middleware.Recover())
  17. // CORS default
  18. // Allows requests from any origin wth GET, HEAD, PUT, POST or DELETE method.
  19. // e.Use(middleware.CORS())
  20. // CORS restricted
  21. // Allows requests from any `https://labstack.com` or `https://labstack.net` origin
  22. // wth GET, PUT, POST or DELETE method.
  23. e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  24. AllowOrigins: []string{"https://labstack.com", "https://labstack.net"},
  25. AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
  26. }))
  27. e.GET("/api/users", getUsers)
  28. e.Logger.Fatal(e.Start(":1323"))
  29. }