简体   繁体   中英

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. I see 2 cases:

  • using strings.Split() , Trim() and etc (I think it's not good idea)
  • using bufio.Scanner with SplitFunc (little bit better)

Any good idea or best practice?

Edit 1. Using 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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