What's the difference between ResponseWriter.Write and io.WriteString?

后端 未结 2 1489
粉色の甜心
粉色の甜心 2020-12-12 22:16

I\'ve seen three ways of writing content to HTTP response:

func Handler(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, \"blabla.\\n\")
}
<         


        
2条回答
  •  离开以前
    2020-12-12 22:56

    As you can see from here(ResponseWriter), that it is a interface with Write([]byte) (int, error) method.

    So in io.WriteString and fmt.Fprintf both are taking Writer as 1st argument which is also a interface wrapping Write(p []byte) (n int, err error) method

    type Writer interface {
        Write(p []byte) (n int, err error)
    }
    

    So when you call io.WriteString(w,"blah") check here

    func WriteString(w Writer, s string) (n int, err error) {
      if sw, ok := w.(stringWriter); ok {
          return sw.WriteString(s)
      }
      return w.Write([]byte(s))
    }
    

    or fmt.Fprintf(w, "blabla") check here

    func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
       p := newPrinter()
       p.doPrintf(format, a)
       n, err = w.Write(p.buf)
       p.free()
       return
    }
    

    you are just calling Write Method indirectly as you are passing ResponseWriter variable in both methods.

    So just why not call it directly using w.Write([]byte("blabla\n")). I hope you got your answer.

    PS: there's also a different way to use that, if you want to send it as JSON response.

    json.NewEncoder(w).Encode(wrapper)
    //Encode take interface as an argument. Wrapper can be:
    //wrapper := SuccessResponseWrapper{Success:true, Data:data}
    

提交回复
热议问题