日志
```
[Debug] 2016-05-28 19:47:10.812379321 +0800 CST get file handler: GET /16,2019fe6c23
[Debug] 2016-05-28 19:47:10.967188428 +0800 CST get file handler: GET /16,2019fe6c23
```
简要代码
```
http.HandleFunc("/submit", submitHandler)
http.HandleFunc("/", getFileHandler)
e := http.ListenAndServe(listeningAddress, nil)
if e != nil {
log.Error("Weeder Proxy startup error: ", e)
}
```
getFileHandler 方法中通过http.Get(url) 读取了另外一个网址的图片,然后返回给当前调用的客户端,
奇怪的是从日志看为什么每次调用都会被执行两三次?
请问有人遇到过这个问题么?
先谢谢各位了。
源码
```
package main
import (
"bytes"
log "fmt"
"io"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/submit", submitHandler)
http.HandleFunc("/", getFileHandler)
e := http.ListenAndServe("0.0.0.0:9330", nil)
if e != nil {
log.Println("Weeder Proxy startup error: ", e)
}
}
func submitHandler(w http.ResponseWriter, r *http.Request) {
log.Println("submit handler: ", r.Method, " ", r.RequestURI)
}
func getFileHandler(w http.ResponseWriter, r *http.Request) {
log.Println("get file handler: ", r.Method, " ", r.RequestURI)
err := download("https://www.baidu.com/img/bd_logo1.png", w, r)
// var err error = nil
if err != nil {
log.Println("download: ", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("{\"error\":\"Can't get the file!\"}"))
} else {
log.Println("get file handler: ", r.Method, " ", r.RequestURI, "success.")
}
}
func download(url string, w http.ResponseWriter, r *http.Request) error {
defer func() {
if r := recover(); r != nil {
log.Println("download: ", r)
}
}()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
/**
* ioutil.ReadAll(resp.Body)
* 会将文件整个读取到内存中后才返回,如果文件较大或并发访问量较大,需要注意
*/
pix, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return writeResponseContent(bytes.NewReader(pix), resp, w, r)
// pix, err := ioutil.ReadFile("/apps/gopath/src/qianbao.com/weeder/explain-it-simply.jpg")
// if err != nil {
// return err
// }
// var resp *http.Response = nil
// return ps.writeResponseContent(bytes.NewReader(pix), int64(len(pix)), resp, w, r)
}
func writeResponseContent(
rs io.ReadSeeker, resp *http.Response,
w http.ResponseWriter, r *http.Request) error {
var e error = nil
mimeType := ""
if resp != nil {
mimeType = resp.Header.Get("Content-Type")
w.Header().Set("Content-Type", mimeType)
w.Header().Set("Content-Disposition", resp.Header.Get("Content-Disposition"))
w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
}
w.Header().Set("Accept-Ranges", "bytes")
rangeReq := r.Header.Get("Range")
if rangeReq == "" {
_, e = io.Copy(w, rs)
return e
}
return e
}
```
更多评论