github.com/waldiirawan/apm-agent-go/v2@v2.2.2/internal/apmhttputil/forwarded.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package apmhttputil 19 20 import ( 21 "strconv" 22 "strings" 23 ) 24 25 // ForwardedHeader holds information extracted from a "Forwarded" HTTP header. 26 type ForwardedHeader struct { 27 For string 28 Host string 29 Proto string 30 } 31 32 // ParseForwarded parses a "Forwarded" HTTP header. 33 func ParseForwarded(f string) ForwardedHeader { 34 // We only consider the first value in the sequence, 35 // if there are multiple. Disregard everything after 36 // the first comma. 37 if comma := strings.IndexRune(f, ','); comma != -1 { 38 f = f[:comma] 39 } 40 var result ForwardedHeader 41 for f != "" { 42 field := f 43 if semi := strings.IndexRune(f, ';'); semi != -1 { 44 field = f[:semi] 45 f = f[semi+1:] 46 } else { 47 f = "" 48 } 49 eq := strings.IndexRune(field, '=') 50 if eq == -1 { 51 // Malformed field, ignore. 52 continue 53 } 54 key := strings.TrimSpace(field[:eq]) 55 value := strings.TrimSpace(field[eq+1:]) 56 if len(value) > 0 && value[0] == '"' { 57 var err error 58 value, err = strconv.Unquote(value) 59 if err != nil { 60 // Malformed, ignore 61 continue 62 } 63 } 64 switch strings.ToLower(key) { 65 case "for": 66 result.For = value 67 case "host": 68 result.Host = value 69 case "proto": 70 result.Proto = value 71 } 72 } 73 return result 74 }