ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

golang 文件流转发

2020-10-26 02:01:45  阅读:19  来源: 互联网

标签:文件 http nil err res golang func 转发 com


....占位

copy from  

https://www.jianshu.com/p/10c857270947

https://www.jianshu.com/p/55b0b8126e40?utm_campaign=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com

https://www.codercto.com/a/48060.html

// dataServer.go
package main

import (
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

const objectDir = "./objects/"

var (
	url = "http://1.1.13.10:9800/huzh1310.txt"
)

func Handler(w http.ResponseWriter, r *http.Request) {
	m := r.Method
	if m == http.MethodGet {
		get(w, r)
		return
	}
	w.WriteHeader(http.StatusMethodNotAllowed)
	w.Header().Set("content-disposition", "attachment;filename=aa.txt")
}

func get(w http.ResponseWriter, r *http.Request) {
	// 收到 接口服务器的 请求
	// 提取 要获取的文件名
	name := strings.Split(r.URL.EscapedPath(), "/")[2]
	f, e := os.Open(objectDir + name)
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusNotFound)
		return
	}
	defer f.Close()
	res, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	// 真正读取,并发送

	//文件流写入
	//io.Copy(w, f)

	//http 流写入
	io.Copy(w, res.Body)
}

func getURL() {
	res, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	f, err := os.Create("huzh1310_local.txt")
	if err != nil {
		panic(err)
	}
	io.Copy(f, res.Body)
}

func main() {
	http.HandleFunc("/objects/", Handler)
	http.ListenAndServe(":8889", nil)
	getURL()

}

  

 待补充, golang http response header

标签:文件,http,nil,err,res,golang,func,转发,com
来源: https://www.cnblogs.com/eiguleo/p/13876228.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有