service_matcher-go/http/http.go

86 lines
1.6 KiB
Go
Raw Normal View History

2018-08-13 07:48:32 +00:00
package http
import (
"strings"
2018-08-15 07:17:18 +00:00
osm "git.loafle.net/overflow/service_matcher-go"
2018-08-13 07:48:32 +00:00
)
type HTTPMatcher struct {
2018-08-15 07:17:18 +00:00
osm.Matchers
2018-08-13 07:48:32 +00:00
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) Key() string {
2018-08-13 07:48:32 +00:00
return "HTTP"
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) Name(matchCtx *osm.MatchCtx) string {
2018-08-13 07:48:32 +00:00
name := "HTTP"
2018-09-03 13:36:57 +00:00
if v, ok := matchCtx.GetAttribute("server"); ok {
name = name + " (" + v.(string) + ")"
2018-08-13 07:48:32 +00:00
}
return name
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) IsPrePacket(matchCtx *osm.MatchCtx) bool {
2018-08-13 07:48:32 +00:00
return false
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) HasResponse(matchCtx *osm.MatchCtx, index int) bool {
2018-08-13 07:48:32 +00:00
return true
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) IsError(matchCtx *osm.MatchCtx, index int, packet *osm.Packet) bool {
2018-08-13 07:48:32 +00:00
return false
}
2018-09-03 13:36:57 +00:00
func (m *HTTPMatcher) Match(matchCtx *osm.MatchCtx, index int, packet *osm.Packet) error {
2018-08-13 07:48:32 +00:00
2018-09-03 06:42:56 +00:00
if packet == nil || !packet.Valid() {
2018-08-15 07:17:18 +00:00
return osm.NoPacketReceivedError()
2018-08-13 07:48:32 +00:00
}
2018-09-03 06:42:56 +00:00
str := string(packet.Bytes())
2018-08-13 07:48:32 +00:00
elems := strings.Split(str, "\r\n")
if len(elems) <= 0 || 9 > len(elems[0]) {
2018-08-15 07:17:18 +00:00
return osm.NotMatchedError()
2018-08-13 07:48:32 +00:00
}
protocol := (elems[0])[:8]
if !strings.HasPrefix(protocol, "HTTP/") {
2018-08-15 07:17:18 +00:00
return osm.NotMatchedError()
2018-08-13 07:48:32 +00:00
}
serverName := ""
for _, valueStr := range elems {
tempElems := strings.Split(valueStr, ":")
if 0 == strings.Compare(tempElems[0], "Server") {
serverName = strings.TrimSpace(tempElems[1])
break
}
}
2018-09-03 13:36:57 +00:00
matchCtx.SetAttribute("protocol_version", protocol)
2018-08-13 07:48:32 +00:00
if len(serverName) > 0 {
2018-09-03 13:36:57 +00:00
matchCtx.SetAttribute("server", serverName)
2018-08-13 07:48:32 +00:00
}
return nil
}
2018-08-15 07:17:18 +00:00
func NewMatcher() osm.Matcher {
2018-08-13 07:48:32 +00:00
m := &HTTPMatcher{}
reqStr := "GET / HTTP/1.1\r\n\r\n"
byte := make([]byte, len(reqStr))
copy(byte[:], reqStr)
2018-08-15 07:17:18 +00:00
m.AddPacket(osm.NewPacket(byte, len(reqStr)))
2018-08-13 07:48:32 +00:00
return m
}