7.8 http redirected



package main

import (
	"fmt"
	"net/http"
)

const addr = "localhost:7070"

type RedirecServer struct {
	redirectCount int
}

func (s *RedirecServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	s.redirectCount++
	fmt.Println("Received header: " + req.Header.Get("Known-redirects"))
	http.Redirect(rw, req, fmt.Sprintf("/redirect%d", s.redirectCount), http.StatusTemporaryRedirect)
}

func main() {
	s := http.Server{
		Addr:    addr,
		Handler: &RedirecServer{0},
	}
	go s.ListenAndServe()

	client := http.Client{}
	redirectCount := 0

	// If the count of redirects is reached
	// than return error.
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		fmt.Println("Redirected")
		if redirectCount > 2 {
			return fmt.Errorf("Too many redirects")
		}
		req.Header.Set("Known-redirects", fmt.Sprintf("%d", redirectCount))
		redirectCount++
		for _, prReq := range via {
			fmt.Printf("Previous request: %v\n", prReq.URL)
		}
		return nil
	}

	_, err := client.Get("http://" + addr)
	if err != nil {
		panic(err)
	}
}

/*

Received header: 
Redirected
Previous request: http://localhost:7070
Received header: 0
Redirected
Previous request: http://localhost:7070
Previous request: http://localhost:7070/redirect1
Received header: 1
Redirected
Previous request: http://localhost:7070
Previous request: http://localhost:7070/redirect1
Previous request: http://localhost:7070/redirect2
Received header: 2
Redirected
panic: Get /redirect4: Too many redirects

goroutine 1 [running]:
main.main()
	/Users/zrd/Desktop/go/go_path/src/go_web/xml.go:47 +0x238
 */

posted on 2018-03-24 00:00  cucy_to  阅读(180)  评论(0编辑  收藏  举报

导航