使用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
}

猜你喜欢

转载自www.cnblogs.com/MyUniverse/p/11273566.html