service_matcher-go/http/http.go
crusader d5bc04d5ee ing
2018-09-03 22:41:28 +09:00

86 lines
1.6 KiB
Go

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