• golang web服务器处理前端HTTP请求跨域的方法


    直接上代码:)

    package main

    import (
    "flag"
    "fmt"
    "net"
    "net/http"
    )

    type httpServer struct {
    }

    func (s *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // Stop here if its Preflighted OPTIONS request
    if origin := r.Header.Get("Origin"); origin != "" {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    w.Header().Set("Access-Control-Allow-Headers",
    "Action, Module")   //有使用自定义头 需要这个,Action, Module是例子
    }

    if r.Method == "OPTIONS" {
    return
    }

    w.Write([]byte("hello"))
    }

    func main() {
    addr := flag.String("http-address", "", "")
    flag.Parse()

    var h httpServer

    httpListener, err := net.Listen("tcp", *addr)
    server := http.Server{
    Handler: &h,
    }
    server.Serve(httpListener)

    fmt.Println("finish ", err)
    }

  • 相关阅读:
    CF1137C Museums Tour(tarjan+DP)
    Educational Codeforces Round 65 (Rated for Div. 2)
    Codeforces Round #559(Div.1)
    委托
    类库
    is 和 as 运算符
    面向对象 接口
    抽象类
    面向对象 多态
    访问修饰符 程序集 静态方法
  • 原文地址:https://www.cnblogs.com/chukuang2004/p/5595219.html
Copyright © 2020-2023  润新知