使用go开启一个能够提供给html的a标签的下载的后端
生活随笔
收集整理的這篇文章主要介紹了
使用go开启一个能够提供给html的a标签的下载的后端
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package main
import( "encoding/json" "fmt" "io/ioutil" "net/http" )
func main(){ fmt.Println("將自己的電腦轉(zhuǎn)化為服務(wù)端") // http.Handle("/",http.FileServer()) http.Handle("/sr/",http.StripPrefix("/sr/",http.FileServer(http.Dir("../src")))) //Dir只能訪問到根目錄,只有使用StripPrefix的時(shí)候才能解析到當(dāng)前運(yùn)行文件下的所有文件 http.HandleFunc("/test",ReceiveFile) http.ListenAndServe(":8080",nil) }
func ReceiveFile(w http.ResponseWriter,r *http.Request){ CrossDomain(w) if r.Method!="POST" { return } var data interface{} body,err := ioutil.ReadAll(r.Body) if err!=nil{ panic(err) } err = json.Unmarshal(body,&data) if err!=nil{ panic(err) } // fmt.Println(data) }
func CrossDomain(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") //允許訪問所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的類型 w.Header().Set("content-type", "application/json") //返回?cái)?shù)據(jù)格式是json }
import( "encoding/json" "fmt" "io/ioutil" "net/http" )
func main(){ fmt.Println("將自己的電腦轉(zhuǎn)化為服務(wù)端") // http.Handle("/",http.FileServer()) http.Handle("/sr/",http.StripPrefix("/sr/",http.FileServer(http.Dir("../src")))) //Dir只能訪問到根目錄,只有使用StripPrefix的時(shí)候才能解析到當(dāng)前運(yùn)行文件下的所有文件 http.HandleFunc("/test",ReceiveFile) http.ListenAndServe(":8080",nil) }
func ReceiveFile(w http.ResponseWriter,r *http.Request){ CrossDomain(w) if r.Method!="POST" { return } var data interface{} body,err := ioutil.ReadAll(r.Body) if err!=nil{ panic(err) } err = json.Unmarshal(body,&data) if err!=nil{ panic(err) } // fmt.Println(data) }
func CrossDomain(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") //允許訪問所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的類型 w.Header().Set("content-type", "application/json") //返回?cái)?shù)據(jù)格式是json }
轉(zhuǎn)載于:https://www.cnblogs.com/MyUniverse/p/11273566.html
總結(jié)
以上是生活随笔為你收集整理的使用go开启一个能够提供给html的a标签的下载的后端的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。