使用go开启一个能够提供给html的a标签的下载的后端
生活随笔
收集整理的這篇文章主要介紹了
使用go开启一个能够提供给html的a标签的下载的后端
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package main
import( "encoding/json" "fmt" "io/ioutil" "net/http" )
func main(){ fmt.Println("將自己的電腦轉化為服務端") // http.Handle("/",http.FileServer()) http.Handle("/sr/",http.StripPrefix("/sr/",http.FileServer(http.Dir("../src")))) //Dir只能訪問到根目錄,只有使用StripPrefix的時候才能解析到當前運行文件下的所有文件 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") //返回數據格式是json }
import( "encoding/json" "fmt" "io/ioutil" "net/http" )
func main(){ fmt.Println("將自己的電腦轉化為服務端") // http.Handle("/",http.FileServer()) http.Handle("/sr/",http.StripPrefix("/sr/",http.FileServer(http.Dir("../src")))) //Dir只能訪問到根目錄,只有使用StripPrefix的時候才能解析到當前運行文件下的所有文件 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") //返回數據格式是json }
轉載于:https://www.cnblogs.com/MyUniverse/p/11273566.html
總結
以上是生活随笔為你收集整理的使用go开启一个能够提供给html的a标签的下载的后端的全部內容,希望文章能夠幫你解決所遇到的問題。