常用类型及数据操作方法
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

3 years ago
3 years ago
  1. package helper
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. /**
  7. * 取访问主机名
  8. */
  9. func GetHost(req *http.Request) string {
  10. var hostlist []string = req.Header.Values("X-Forwarded-Host")
  11. var host string
  12. if len(hostlist) > 1 {
  13. host = hostlist[len(hostlist)-1] //取最后一次转发的
  14. } else if len(hostlist) == 1 {
  15. host = hostlist[0]
  16. } else {
  17. host = ""
  18. }
  19. if host != "" {
  20. hosts := strings.Split(host, ",")
  21. host = strings.Trim(hosts[len(hosts)-1], " ")
  22. }
  23. if host == "" {
  24. host = req.Host
  25. }
  26. return host
  27. }
  28. /**
  29. * 取域名
  30. */
  31. func GetDomain(req *http.Request) string {
  32. scheme := "http://"
  33. if req.TLS != nil {
  34. scheme = "https://"
  35. }
  36. if strings.Contains(req.Referer(), "https://") {
  37. scheme = "https://"
  38. }
  39. var host string = GetHost(req)
  40. hosts := strings.Split(host, ":")
  41. host = hosts[0]
  42. if hosts[1] == "443" {
  43. scheme = "https://"
  44. }
  45. var w strings.Builder
  46. w.WriteString(scheme)
  47. w.WriteString(host)
  48. return w.String()
  49. }
  50. func SetHeader(w http.ResponseWriter, resp *http.Request) {
  51. w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
  52. w.Header().Add("Access-Control-Allow-Headers", "Content-Type,x-csrf-token,x-requested-with,token") //header的类型
  53. w.Header().Set("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
  54. w.Header().Set("content-type", "application/json") //返回数据格式是json
  55. // w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
  56. }