Golang笔记

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

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

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)
}

本文网址: https://golangnote.com/topic/189.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles