github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/http/header-content-type.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package http
     4  
     5  // ContentType store
     6  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
     7  type ContentType struct {
     8  	Type     mimeType
     9  	SubType  mimeSubType
    10  	Charset  string
    11  	Boundary string
    12  }
    13  
    14  // ContentType read all value about content in header
    15  func (h *header) ContentType() (c ContentType) {
    16  	var contentType = h.Get(HeaderKeyContentType)
    17  	return getContentType(contentType)
    18  }
    19  
    20  // getContentType read all value about content in header
    21  func getContentType(contentType string) (c ContentType) {
    22  	var mediaTypeFirst, mediaTypeSecond string
    23  	var index int
    24  	for i := 0; i < len(contentType); i++ {
    25  		switch contentType[i] {
    26  		case '/':
    27  			mediaTypeFirst = contentType[:i]
    28  			index = i + 1
    29  		case ';':
    30  			mediaTypeSecond = contentType[index:i]
    31  			contentType = contentType[i+2:] // +2 due to have space after semicolon
    32  		}
    33  	}
    34  
    35  	switch contentType[0] {
    36  	case 'c': // charset=
    37  		c.Charset = contentType[8:]
    38  	case 'b': // boundary=
    39  		c.Boundary = contentType[9:]
    40  	}
    41  
    42  	switch mediaTypeFirst {
    43  	case "text":
    44  		c.Type = ContentTypeMimeTypeText
    45  	case "application":
    46  		c.Type = ContentTypeMimeTypeApplication
    47  	}
    48  
    49  	switch mediaTypeSecond {
    50  	case "html":
    51  		c.SubType = ContentTypeMimeSubTypeHTML
    52  	case "json":
    53  		c.SubType = ContentTypeMimeSubTypeJSON
    54  	}
    55  
    56  	return
    57  }
    58  
    59  type mimeType uint16
    60  
    61  // Standard HTTP content type
    62  const (
    63  	ContentTypeMimeTypeUnset mimeType = iota
    64  	ContentTypeMimeTypeText
    65  	ContentTypeMimeTypeApplication
    66  )
    67  
    68  type mimeSubType uint16
    69  
    70  // Standard HTTP content type
    71  const (
    72  	ContentTypeMimeSubTypeUnset mimeSubType = iota
    73  	ContentTypeMimeSubTypeHTML
    74  	ContentTypeMimeSubTypeJSON
    75  )