1. 程式人生 > 其它 >Golang web伺服器處理前端HTTP請求跨域的方法

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)
}