来源:http://www.shanhubei.com/archives/2838.html
直接上代码
package main import ( "fmt" "io/ioutil" "net/http" ) //获取C的图片数据 func ReadImgData(url string) []byte { resp, err := http.Get(url) if err != nil { panic(err) } defer resp.Body.Close() pix, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } return pix } func myWeb(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型 //w.Header().Set("content-type", "application/json") //返回数据格式是json query := r.URL.Query(); var url string; var name string; if len(query["url"]) > 0{ url = query["url"][0] }else { fmt.Fprintf(w, ""); return ; } if len(query["name"]) > 0{ name = query["name"][0]; w.Header().Set("content-type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename=" + name) } fmt.Println(url,name); pix := ReadImgData(url); w.Write(pix ) //fmt.Fprintf(w, "这是一个开始"); } func main() { http.HandleFunc("/", myWeb) fmt.Println("服务器即将开启,访问地址 http://localhost:3000") err := http.ListenAndServe(":3000", nil) if err != nil { fmt.Println("服务器开启错误: ", err) } }
调用方式:
<img src="http://localhost:3000?url=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F32f065b3afb3fb36b75a5cbc90051b1050e1e6b6e199-Ml6q9F_fw320&name=test.jpg" >
标签:http,跨域,err,url,fmt,问题,go,query,name From: https://www.cnblogs.com/shanhubei/p/17837909.html