简体   繁体   English

带有多个值的golang http解析头

[英]golang http parsing header with multiple values

How can I obtain value from header that have multiple comma separated values. 如何从具有多个逗号分隔值的标头中获取值。 For instance, 例如,

url := "https://accounts.google.com/.well-known/openid-configuration"
resp, err := http.Get(url)
field := resp.Header.Get("Cache-Control") // "public, max-age=3600"

In this case I want get max-age value. 在这种情况下,我想获得max-age值。 I see 2 cases: 我看到2种情况:

  • using strings.Split() , Trim() and etc (I think it's not good idea) 使用strings.Split()Trim()等(我认为这不是一个好主意)
  • using bufio.Scanner with SplitFunc (little bit better) bufio.ScannerSplitFunc bufio.Scanner使用(稍微好一点)

Any good idea or best practice? 有什么好主意或最佳做法吗?

Edit 1. Using strings.FieldsFunc() 编辑1.使用strings.FieldsFunc()

const input = "   public,max-age=3000,   anothercase   "

sep := func(c rune) bool {
    return c == ',' || c == ' '
}
values := strings.FieldsFunc(input, sep)

Regarding benchmarks 关于基准

BenchmarkTrim-4  2000000  861 ns/op  48 B/op  1 allocs/op

Edit 2. Using Scaner() 编辑2.使用Scaner()

So lets benchmark it 因此,让它进行基准测试

func ScanHeaderValues(data []byte, atEOF bool) (advance int, token []byte, err error) {
    // Skip leading spaces.
    var start int
    for start = 0; start < len(data); start++ {
        if data[start] != ' ' {
            break
        }
    }
    // Scan until comma
    for i := start; i < len(data); i++ {
        if data[i] == ',' {
            return i + 1, data[start:i], nil
        }
    }
    // If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
    if atEOF && len(data) > start {
        return len(data), data[start:], nil
    }
    // Request more data.
    return start, nil, nil
}

func BenchmarkScanner(b *testing.B) {
    const input = "   public,max-age=3000,   anothercase   "
    scanner := bufio.NewScanner(strings.NewReader(input))
    split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
        advance, token, err = ScanHeaderValues(data, atEOF)
        return
    }
    scanner.Split(split)

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        for scanner.Scan() {
            // a := scanner.Text()
            // b.Logf("%+v\n", a)
        }
    }
}

And result: 结果:

BenchmarkTrim-4     2000000   861  ns/op  48 B/op  1 allocs/op
BenchmarkScanner-4  50000000  21.2 ns/op  0  B/op  0 allocs/op

If you have any other better solution I would like see it. 如果您还有其他更好的解决方案,我希望看到它。

Nothing wrong with: 没问题:

url := "https://accounts.google.com/.well-known/openid-configuration"
resp, err := http.Get(url)
fields := strings.Split(resp.Header.Get("Cache-Control"), ",")
for i, field := range field {
    fields[i] = strings.Trim(field, " ")
}

Edit: Edit now works if space after comma is missing 编辑:如果缺少逗号后的空格,则编辑现在可以进行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM