常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

65 lines
1.4 KiB

package helper
import (
"net/http"
"strings"
)
/**
* 取访问主机名
*/
func GetHost(req *http.Request) string {
var hostlist []string = req.Header.Values("X-Forwarded-Host")
var host string
if len(hostlist) > 1 {
host = hostlist[len(hostlist)-1] //取最后一次转发的
} else if len(hostlist) == 1 {
host = hostlist[0]
} else {
host = ""
}
if host != "" {
hosts := strings.Split(host, ",")
host = strings.Trim(hosts[len(hosts)-1], " ")
}
if host == "" {
host = req.Host
}
return host
}
/**
* 取域名
*/
func GetDomain(req *http.Request) string {
scheme := "http://"
if req.TLS != nil {
scheme = "https://"
}
if strings.Contains(req.Referer(), "https://") {
scheme = "https://"
}
var host string = GetHost(req)
hosts := strings.Split(host, ":")
host = hosts[0]
if hosts[1] == "443" {
scheme = "https://"
}
var w strings.Builder
w.WriteString(scheme)
w.WriteString(host)
return w.String()
}
func SetHeader(w http.ResponseWriter, resp *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type,x-csrf-token,x-requested-with,token") //header的类型
w.Header().Set("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
w.Header().Set("content-type", "application/json") //返回数据格式是json
// w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
}