前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >GoFrame 框架(rk-boot): 快速配置服务端 CORS

GoFrame 框架(rk-boot): 快速配置服务端 CORS

原创
作者头像
尹东勋
发布2022-02-03 16:55:12
4090
发布2022-02-03 16:55:12
举报

介绍

本文介绍如何通过 rk-boot 快速配置服务端 CORS。

什么是 CORS? 跨源资源共享 (CORS) (或通俗地译为跨域资源共享)是一种基于HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其它origin(域,协议和端口),这样浏览器可以访问加载这些资源。

请访问如下地址获取完整教程:

安装

go get github.com/rookie-ninja/rk-boot/gf

快速开始

1.创建 boot.yaml

boot.yaml 文件会告诉 rk-boot 如何启动 gogf/gf 服务。

在这个例子中,我们只允许 localhost:8080 发送过来的请求,通过验证。

---
gf:
  - name: greeter                     # Required
    port: 8080                        # Required
    enabled: true                     # Required
    interceptors:
      cors:
        enabled: true                 # Optional, default: false
        allowOrigins:
          - "http://localhost:8080"   # Optional, default: *

2.创建 main.go

// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main

import (
	"context"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/rookie-ninja/rk-boot"
	"github.com/rookie-ninja/rk-boot/gf"
	"net/http"
)

func main() {
	// Create a new boot instance.
	boot := rkboot.NewBoot()

	// Register handler
	entry := rkbootgf.GetGfEntry("greeter")
	entry.Server.BindHandler("/v1/hello", hello)

	// Bootstrap
	boot.Bootstrap(context.TODO())

	boot.WaitForShutdownSig(context.TODO())
}

func hello(ctx *ghttp.Request) {
	ctx.Response.WriteHeader(http.StatusOK)
	ctx.Response.WriteJson(map[string]string{
		"message": "hello!",
	})
}

3.创建 cors.html

让我们创建一个简单网页,网页里会调用 localhost:8080/v1/hello,我们通过返回结果来验证 CORS。

<!DOCTYPE html>
<html>
<body>

<h1>CORS Test</h1>

<p>Call http://localhost:8080/v1/hello</p>

<script type="text/javascript">
    window.onload = function() {
        var apiUrl = 'http://localhost:8080/v1/hello';
        fetch(apiUrl).then(response => response.json()).then(data => {
            document.getElementById("res").innerHTML = data["message"]
        }).catch(err => {
            document.getElementById("res").innerHTML = err
        });
    };
</script>

<h4>Response: </h4>
<p id="res"></p>

</body>
</html>

4.文件夹结构

.
├── boot.yaml
├── cors.html
├── go.mod
├── go.sum
└── main.go

0 directories, 5 files

5.验证

打开 cors.html,cors.html 会从非 8080 端口发送请求,所以无法通过验证。

6.给 CORS 添加白名单

这次,我们把 allowOrigins 配置成 localhost:*,即,让所有从 localhost 发送的请求,均可以通过。

---
gf:
  - name: greeter                     # Required
    port: 8080                        # Required
    enabled: true                     # Required
    interceptors:
      cors:
        enabled: true                 # Optional, default: false
        allowOrigins:
          - "http://localhost:*"      # Optional, default: *

7.验证

打开 cors.html

完整参数

请参考 gf-cors 获取完整参数列表。

名字

描述

类型

默认值

gf.interceptors.cors.enabled

启动 CORS 拦截器

boolean

false

gf.interceptors.cors.allowOrigins

可通过验证的 Origin 地址。

[]string

*

gf.interceptors.cors.allowMethods

可通过的 http method, 会包含在 OPTIONS 请求的 Header 中。

[]string

All http methods

gf.interceptors.cors.allowHeaders

可通过的 http header, 会包含在 OPTIONS 请求的 Header 中。

[]string

Headers from request

gf.interceptors.cors.allowCredentials

会包含在 OPTIONS 请求的 Header 中。

bool

false

gf.interceptors.cors.exposeHeaders

会包含在 OPTIONS 请求的 Header 中的 Header。

[]string

""

gf.interceptors.cors.maxAge

会包含在 OPTIONS 请求的 Header 中的 MaxAge。

int

0

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 安装
  • 快速开始
    • 1.创建 boot.yaml
      • 2.创建 main.go
        • 3.创建 cors.html
          • 4.文件夹结构
            • 5.验证
              • 6.给 CORS 添加白名单
                • 7.验证
                • 完整参数
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档