http.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package l7
  2. import (
  3. "bytes"
  4. "strconv"
  5. "strings"
  6. )
  7. func ParseHttp(payload []byte) (string, string) {
  8. method, rest, ok := bytes.Cut(payload, space)
  9. if !ok {
  10. return "", ""
  11. }
  12. if !isHttpMethod(string(method)) {
  13. return "", ""
  14. }
  15. uri, _, ok := bytes.Cut(rest, space)
  16. if !ok {
  17. uri = append(uri, []byte("...")...)
  18. }
  19. return string(method), string(uri)
  20. }
  21. func ParseHttpHost(payload []byte, isTls bool) (string, string, string, uint16) {
  22. method, rest, ok := bytes.Cut(payload, space)
  23. if !ok {
  24. return "", "", "", 0
  25. }
  26. if !isHttpMethod(string(method)) {
  27. return "", "", "", 0
  28. }
  29. uri, rest, ok := bytes.Cut(rest, space)
  30. if !ok {
  31. uri = append(uri, []byte("...")...)
  32. }
  33. //hostStart := bytes.Index(rest, []byte("Host:")) + len("Host:")
  34. hostHeader := "Host:"
  35. hostIdx := bytes.Index(rest, []byte(hostHeader))
  36. if hostIdx == -1 {
  37. return string(method), string(uri), "", 0
  38. }
  39. hostStart := hostIdx + len(hostHeader)
  40. hostEnd := bytes.Index(rest[hostStart:], []byte("\r\n"))
  41. var hostPortBts []byte
  42. if hostEnd == -1 {
  43. hostPortBts = rest[hostStart:]
  44. } else {
  45. hostPortBts = rest[hostStart : hostStart+hostEnd]
  46. }
  47. hostPort := string(bytes.TrimSpace(hostPortBts))
  48. hostParts := strings.Split(hostPort, ":")
  49. host := hostParts[0]
  50. // 根据 TLS 标识设置默认端口
  51. var port uint16
  52. if isTls {
  53. port = 443 // HTTPS 默认端口
  54. } else {
  55. port = 80 // HTTP 默认端口
  56. }
  57. // 如果 Host 头部明确指定了端口,使用指定的端口
  58. if len(hostParts) > 1 {
  59. port64, err := strconv.ParseUint(hostParts[1], 10, 16)
  60. if err == nil {
  61. port = uint16(port64)
  62. }
  63. }
  64. return string(method), string(uri), host, port
  65. }