Golang setting HTTP response response headers and pits

Source: Internet
Author: User

1, set the order of Writeheader problem

Before encountering a problem, in a piece of code to set the Writeheader, and finally in the header to take the name of how can not be taken.

w.WriteHeader(201)w.Header().Set("Name", "my name is smallsoup")

When writing HTTP server with Golang, it is convenient to set the contents of the Header in HTTP response by W.header.set (K, v). However, it is important to note that some time not only to modify the response header, but also to modify the response statuscode. Modifying the response statuscode can be done by: W. Writeheader (code) to implement, for example:

w.WriteHeader(404)

If these two modifications are done together, the W.writeheader must be left behind after all W.header.set because the Set Header is invalid after W.writeheader.

and must be before W.write ([]byte ("HelloWorld")), otherwise http:multiple response will be reported. Writeheader calls because actually called W. Write will also call the Writeheader () method, and then set W.wroteheader to True, again Writeheader () will be judged Wroteheader, if True will error, and this call does not take effect.

You can see the following source code description Writeheader must be called before write.

func (w *response) WriteHeader(code int) { if w.conn.hijacked() {   w.conn.server.logf("http: response.WriteHeader on hijacked connection")   return }//第二次WriteHeader()进来满足if条件就报错直接return if w.wroteHeader {   w.conn.server.logf("http: multiple response.WriteHeader calls")   return }//第一次write()进来这里会将w.wroteHeader置为true w.wroteHeader = true w.status = code if w.calledHeader && w.cw.header == nil {   w.cw.header = w.handlerHeader.clone() } if cl := w.handlerHeader.get("Content-Length"); cl != "" {   v, err := strconv.ParseInt(cl, 10, 64)   if err == nil && v >= 0 {     w.contentLength = v   } else {     w.conn.server.logf("http: invalid Content-Length of %q", cl)     w.handlerHeader.Del("Content-Length")   } }}

2, go will be the key in the header to standardize processing

Go will normalize the key in the header, so be careful when you get the K,v value in the header of response.

Reader.go non-export method Canonicalmimeheaderkey There is such a paragraph, the header key will be normalized processing.

1) The istokentable array is defined in Reader.go, and if the key is longer than 127 or contains characters that are not in istokentable, the key is not processed.

2) Capitalize the first letter of the key, and the first letter of the character-after word.

Analysis of the following source code, you can explain the capitalization of key processing:

for i, c := range a {  // 规范化:首字母大写  // - 之后单子的首字母大写  // 如:(Host, User-Agent, If-Modified-Since).  if upper && 'a' <= c && c <= 'z' {    //大写转小写    c -= toLower  } else if !upper && 'A' <= c && c <= 'Z' {    //小写转大写    c += toLower  }  //重新给key数组赋值  a[i] = c  //设置大小写标志位  upper = c == '-' // for next time}

The correct way to call:

Server: Myserver.go

package mainimport ( "net/http")func main() { http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request){   w.Header().Set("name", "my name is smallsoup")   w.WriteHeader(500)   w.Write([]byte("hello world\n")) }) http.ListenAndServe(":8080", nil)}

Client:

Myhttp.go:

package mainimport ( "fmt" "io/ioutil" "net/http")func main() { myHttpGet()}func myHttpGet() { rsp, err := http.Get("http://localhost:8080") if err != nil {   fmt.Println("myHttpGet error is ", err)   return } defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) if err != nil {   fmt.Println("myHttpGet error is ", err)   return } fmt.Println("response statuscode is ", rsp.StatusCode,          "\nhead[name]=", rsp.Header["Name"],            "\nbody is ", string(body))}

1. Running the server

Go Run myserver.go

2. Running the client

Go Run myhttp.go

The output is as follows: StatusCode is the value we set for the 500,name also taken.

Image

About Go, Docker, k8s related learning resources follow the public number after the end of the article reply to "1" get

Finally, CSDN resources, collected a huge amount of learning materials, if you are ready into it pit, inspirational to become a good program ape, then these resources are suitable for you, including Java, go, Python, springcloud, elk, embedded, big data, interview materials, front-end and other resources. At the same time we formed a technical exchange group, there are many big guys, will not regularly share technical articles, if you want to learn to improve together, you can pay attention to the following public number after the reply "2", access.

I am a small bowl of soup, we study together, sweep code attention, wonderful content the first time to push you

Welcome to Scan Code attention

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.