github.com/qiniu/x@v1.11.9/httputil/httputil.go (about)

     1  /*
     2   Copyright 2022 Qiniu Limited (qiniu.com)
     3  
     4   Licensed under the Apache License, Version 2.0 (the "License");
     5   you may not use this file except in compliance with the License.
     6   You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10   Unless required by applicable law or agreed to in writing, software
    11   distributed under the License is distributed on an "AS IS" BASIS,
    12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   See the License for the specific language governing permissions and
    14   limitations under the License.
    15  */
    16  
    17  package httputil
    18  
    19  import (
    20  	"encoding/json"
    21  	"io"
    22  	"log"
    23  	"net/http"
    24  	"strconv"
    25  )
    26  
    27  // ----------------------------------------------------------
    28  
    29  // Reply replies a http request with a json response.
    30  func Reply(w http.ResponseWriter, code int, data interface{}) {
    31  	msg, err := json.Marshal(data)
    32  	if err != nil {
    33  		panic(err)
    34  	}
    35  	h := w.Header()
    36  	h.Set("Content-Length", strconv.Itoa(len(msg)))
    37  	h.Set("Content-Type", "application/json")
    38  	w.WriteHeader(code)
    39  	w.Write(msg)
    40  }
    41  
    42  // ReplyWith replies a http request with a bodyType response.
    43  func ReplyWith(w http.ResponseWriter, code int, bodyType string, msg []byte) {
    44  	h := w.Header()
    45  	h.Set("Content-Length", strconv.Itoa(len(msg)))
    46  	h.Set("Content-Type", bodyType)
    47  	w.WriteHeader(code)
    48  	w.Write(msg)
    49  }
    50  
    51  // ReplyWithStream replies a http request with a streaming response.
    52  func ReplyWithStream(w http.ResponseWriter, code int, bodyType string, body io.Reader, bytes int64) {
    53  	h := w.Header()
    54  	h.Set("Content-Length", strconv.FormatInt(bytes, 10))
    55  	h.Set("Content-Type", bodyType)
    56  	w.WriteHeader(code)
    57  	// We don't use io.CopyN: if you need, call io.LimitReader(body, bytes) by yourself
    58  	written, err := io.Copy(w, body)
    59  	if err != nil || written != bytes {
    60  		log.Printf("ReplyWithStream (bytes=%v): written=%v, err=%v\n", bytes, written, err)
    61  	}
    62  }
    63  
    64  // ----------------------------------------------------------