GolangNote

Golang笔记

goji 路由组、反向代理、中间件简单示例

Permalink

goji 路由组、反向代理、中间件这几个功能放在一个实例里的示例

goji 路由组、反向代理、中间件简单示例

Go: goji 路由组、反向代理、中间件示例
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

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

	"github.com/golang/glog"
	"goji.io"
	"goji.io/pat"
)

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 hello(w http.ResponseWriter, r *http.Request) {
	name := pat.Param(r, "name")
	fmt.Fprintf(w, "Hello, %s!", name)
}

func hello2(w http.ResponseWriter, r *http.Request) {
	name := pat.Param(r, "name")
	fmt.Fprintf(w, "Hello2, %s!", name)
}

func hello3(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello3, ", "aaa")
}

func main() {
	defer glog.Flush()

	root := goji.NewMux()

	// other
	root.HandleFunc(pat.New("/test/:name"), hello)
	root.HandleFunc(pat.Get("/test2/:name"), hello2)

	proxy := goji.SubMux()
	root.Handle(pat.New("/proxy/*"), proxy)

	other := goji.SubMux()
	root.Handle(pat.New("/other/*"), other)

	//ph := &handle{host: "www.xx.com", port: "80"}
	u, _ := url.Parse("http://www.xx.com/")
	// root.Handle(pat.New("/*"), httputil.NewSingleHostReverseProxy(u))
	root.Handle(pat.New("/pp/*"), http.StripPrefix("/pp/", httputil.NewSingleHostReverseProxy(u)))

	//
	other.HandleFunc(pat.Get("/a"), hello3)
	proxy.HandleFunc(pat.Get("/a"), func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "hahahahshhhsha")
	})

	root.Use(Logger)

	http.ListenAndServe("localhost:8000", root)
}

func Logger(h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("ok")
		h.ServeHTTP(w, r)
		fmt.Println("ok2")
	}
	return http.HandlerFunc(fn)
}

Related articles

Write a Comment to "goji 路由组、反向代理、中间件简单示例"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms