当前位置:网站首页>Goframe framework (RK boot): rapid configuration of server CORS

Goframe framework (RK boot): rapid configuration of server CORS

2022-06-23 02:36:00 Trespass

Introduce

How does this article describe rk-boot Quick configuration server CORS.

What is? CORS? Cross source resource sharing (CORS) ( Cross domain resource sharing ) It's based on HTTP The mechanism of head , The mechanism allows the server to label other than itself origin( Domain , Protocol and port ), So that the browser can access and load these resources .

Please visit the following address for a complete tutorial :

install

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

Quick start

1. establish boot.yaml

boot.yaml The file will tell rk-boot How to start gogf/gf service .

In this case , We only allow localhost:8080 Requests sent , Pass the verification .

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

2. establish 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. establish cors.html

Let's create a simple web page , The web page will call localhost:8080/v1/hello, We verify by returning results 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. Folder structure

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

0 directories, 5 files

5. verification

open cors.html,cors.html Will from non 8080 Port send request , So it doesn't pass the test .

6. to CORS Add whitelist

This time, , We put allowOrigins configure localhost:*, namely , Let all from localhost Sent request , You can go through .

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

7. verification

open cors.html

Complete parameters

Please refer to gf-cors Get the complete parameter list .

name

describe

type

The default value is

gf.interceptors.cors.enabled

start-up CORS Interceptor

boolean

false

gf.interceptors.cors.allowOrigins

Verifiable Origin Address .

[]string

*

gf.interceptors.cors.allowMethods

passable http method, Will be included in OPTIONS Requested Header in .

[]string

All http methods

gf.interceptors.cors.allowHeaders

passable http header, Will be included in OPTIONS Requested Header in .

[]string

Headers from request

gf.interceptors.cors.allowCredentials

Will be included in OPTIONS Requested Header in .

bool

false

gf.interceptors.cors.exposeHeaders

Will be included in OPTIONS Requested Header Medium Header.

[]string

""

gf.interceptors.cors.maxAge

Will be included in OPTIONS Requested Header Medium MaxAge.

int

0

原网站

版权声明
本文为[Trespass ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202031733592665.html