当前位置:网站首页>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 |
边栏推荐
- Automatically update site statistics with actions
- Problem thinking and analysis process
- Call rest port to implement nailing notification
- [target tracking] open source | polytrack: use boundary polygons to quickly track and segment multiple targets, instead of bounding box and mask tracking
- About the use of mock framework
- Aikuai multi dialing + load balancing overlay bandwidth
- await is only valid in async function
- Troubleshooting and optimization of easynvr version 5.0 Video Square snapshot not displayed
- How to batch make decreasing serial number barcode
- The difference between script in head and body
猜你喜欢

Deep learning environment configuration (I) installation of CUDA and cudnn

Application and challenge of ten billion level map data in Kwai security intelligence

5g core network and core network evolution

Soft exam information system project manager_ Contract Law_ Copyright_ Implementation Regulations - Senior Information System Project Manager of soft exam 030

Why is BeanUtils not recommended?

Mobile communication Overview - Architecture

Vs Code inadvertently disable error waveform curve

pd. read_ CSV and np Differences between loadtext

Nebula operator cloud practice

CSDN browser assistant for online translation, calculation, learning and removal of all advertisements
随机推荐
Li Mu's notes on machine learning -1.2
Evolution history of mobile communication
JS rotation chart (Netease cloud rotation chart)
Pywebio to quickly build web applications
Solution to the problem of easycvr switching MySQL database traffic statistics cannot be displayed
【CodeWars】 Pete, the baker
About the use of mock framework
WM view of commodity master data in SAP retail preliminary level
862. triple sorting
Deep learning environment configuration (I) installation of CUDA and cudnn
pd. read_ CSV and np Differences between loadtext
How to locate memory leaks
How to set up an H5 demo of easyplayer locally to play h265 video streams?
Apache Druid's engineering practice in shopee
Delta oscillation in EEG
How to generate DataMatrix code in batch through TXT file
Three ways to get class
Reinforcement learning series (III) -gym introduction and examples
Performance test -- Jenkins environment construction for 15jmeter performance test
Circuit analysis (circuit principle)