GolangNote

Golang笔记

golang 实现反向代理和静态文件服务

Permalink

用 golang 实现两个服务:反向代理服务和静态文件服务。

我用的是goji 框架,

Go: proxy file server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/golang/glog"

	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
)

type handle struct {
	host string
	port string
}

func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	remote, err := url.Parse("http://" + this.host + ":" + this.port)
	if err != nil {
		panic(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)
}

func main() {

	defer glog.Flush()

	// proxy
	h := &handle{host: "www.baidu.com", port: "8080"}
	http.Handle("/proxy/", http.StripPrefix("/proxy/", h))

	// Setup static files
	static := web.New()
	publicPath := "static"
	static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir(publicPath))))

	http.Handle("/static/", static)

	goji.Serve()
}

代理使用 /proxy

静态文件使用 /static

本文网址: https://golangnote.com/topic/132.html 转摘请注明来源

Related articles

golang 实现的基于web的文件管理-filebrowser

FileBrowser 在指定目录中提供了一个文件管理界面,可用于上传,删除,预览,重命名和编辑文件。它允许创建多个用户,每个用户都可以有自己的目录。它可以用作独立的应用程序。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Write a Comment to "golang 实现反向代理和静态文件服务"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms