...

Source file src/github.com/emicklei/go-restful/v3/mime.go

Documentation: github.com/emicklei/go-restful/v3

     1  package restful
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  )
     7  
     8  type mime struct {
     9  	media   string
    10  	quality float64
    11  }
    12  
    13  // insertMime adds a mime to a list and keeps it sorted by quality.
    14  func insertMime(l []mime, e mime) []mime {
    15  	for i, each := range l {
    16  		// if current mime has lower quality then insert before
    17  		if e.quality > each.quality {
    18  			left := append([]mime{}, l[0:i]...)
    19  			return append(append(left, e), l[i:]...)
    20  		}
    21  	}
    22  	return append(l, e)
    23  }
    24  
    25  const qFactorWeightingKey = "q"
    26  
    27  // sortedMimes returns a list of mime sorted (desc) by its specified quality.
    28  // e.g. text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
    29  func sortedMimes(accept string) (sorted []mime) {
    30  	for _, each := range strings.Split(accept, ",") {
    31  		typeAndQuality := strings.Split(strings.Trim(each, " "), ";")
    32  		if len(typeAndQuality) == 1 {
    33  			sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0})
    34  		} else {
    35  			// take factor
    36  			qAndWeight := strings.Split(typeAndQuality[1], "=")
    37  			if len(qAndWeight) == 2 && strings.Trim(qAndWeight[0], " ") == qFactorWeightingKey {
    38  				f, err := strconv.ParseFloat(qAndWeight[1], 64)
    39  				if err != nil {
    40  					traceLogger.Printf("unable to parse quality in %s, %v", each, err)
    41  				} else {
    42  					sorted = insertMime(sorted, mime{typeAndQuality[0], f})
    43  				}
    44  			} else {
    45  				sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0})
    46  			}
    47  		}
    48  	}
    49  	return
    50  }
    51  

View as plain text