+
95
-

golang搭建的http代理服务如何下载指定类型的文件?

go

golang搭建的http代理服务如何下载指定类型的文件?比如所有经过我这个代理观看的视频或图片我都能保存到本地,这个在golang怎么编写代码?

网友回复

+
15
-

golang代码

package main

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

// 代理服务器地址
const proxyAddress = "0.0.0.0:8080"

// 文件下载目录
const downloadDir = "./downloads"

// 要下载的文件类型
var fileTypes = []string{"image/jpeg", "image/png", "application/pdf"}

func main() {
    http.HandleFunc("/", handleRequestAndRedirect)
    fmt.Printf("Starting proxy server on %s\n", proxyAddress)
    if err := http.ListenAndServe(proxyAddress, nil); err != nil {
        fmt.Printf("Failed to start server: %v\n", err)
    }
}

func handleRequestAndRedirect(w http.ResponseWriter, req *http.Request) {
    client := &http.Client{}

    // 创建新的请求
    newReq, err := http.NewRequest(req.Method, req.URL.String(), req.Body)
    if err != nil {
        http.Error(w, "Failed to create request", http.StatusInternalServerError)
        return
    }

    // 复制请求头
    for key, values := range req.Header {
        for _, value := range values {
            newReq.Header.Add(key, value)
        }
    }

    // 发送请求
    resp, err := client.Do(newReq)
    if err != nil {
        http.Error(w, "Failed to get response", http.StatusInternalServerError)
 ...

点击查看剩余70%

我知道答案,我要回答