mime_header_api.mx raw

   1  /*
   2  textproto.MIMEHeader is a named map type, and canonicalization holds.
   3  
   4  `type MIMEHeader map[string][][]byte` carries Add, Set, Get, Values and Del as
   5  methods. A value receiver over a named map is a reference receiver, so the
   6  mutations reach the caller.
   7  
   8  The interesting part of this type is that every operation CANONICALIZES the key
   9  (CanonicalMIMEHeaderKey), which is what makes header lookup case-insensitive -
  10  so the fixture pins that, not just storage: a key written as `x-lower` is found
  11  as `X-LOWER`, and a value written as `Content-Type` is found as `content-type`.
  12  It also pins Get returning the FIRST of several values and Del removing them all.
  13  
  14  net/http.Header's five delegating methods were inlined to direct map operations
  15  in the same round, so this type's methods now have exactly one caller shape:
  16  the free functions below.
  17  */
  18  package main
  19  
  20  import (
  21  	"net/textproto"
  22  )
  23  
  24  func main() {
  25  	// Termination: a batch program must still be stoppable, so the entry
  26  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  27  	select {
  28  	case <-shutdown:
  29  		return
  30  	default:
  31  	}
  32  
  33  	h := textproto.MIMEHeader{}
  34  	h.Set("Content-Type", "text/plain")
  35  	h.Add("X-Multi", "one")
  36  	h.Add("X-Multi", "two")
  37  	h.Set("x-lower", "yes")
  38  	if h.Get("content-type") != "text/plain" {
  39  		panic("get canonicalized key")
  40  	}
  41  	if h.Get("X-LOWER") != "yes" {
  42  		panic("get lower-case written key")
  43  	}
  44  	vs := h.Values("x-multi")
  45  	if len(vs) != 2 || string(vs[1]) != "two" {
  46  		panic("values keeps every value in order")
  47  	}
  48  	h.Del("X-Multi")
  49  	if h.Get("x-multi") != "" {
  50  		panic("del removes every value")
  51  	}
  52  	println("mimeheader ok")
  53  }
  54