[关闭]
@bergus 2016-12-12T18:04:23.000000Z 字数 875 阅读 1745

golang 代理服务器

代理 golang


  1. package main
  2. import (
  3. "net/http"
  4. "log"
  5. "io/ioutil"
  6. "fmt"
  7. )
  8. func handler(w http.ResponseWriter, r *http.Request) {
  9. req, _ := http.NewRequest(r.Method, r.RequestURI, r.Body)
  10. for k, v := range r.Header {
  11. for _, vv := range v {
  12. req.Header.Add(k, vv)
  13. }
  14. }
  15. req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
  16. client := &http.Client{}
  17. resp, err := client.Do(req)
  18. if err!=nil {
  19. fmt.Println("error:",err)
  20. }
  21. defer resp.Body.Close()
  22. for k, v := range resp.Header {
  23. for _, vv := range v {
  24. w.Header().Add(k, vv)
  25. }
  26. }
  27. for _, value := range resp.Request.Cookies() {
  28. w.Header().Add(value.Name,value.Value)
  29. }
  30. w.WriteHeader(resp.StatusCode)
  31. result, err := ioutil.ReadAll(resp.Body)
  32. if (err != nil) {
  33. fmt.Println("error:",err)
  34. }
  35. _,err = w.Write(result)
  36. if (err != nil) {
  37. fmt.Println("error:",err)
  38. }
  39. }
  40. func main() {
  41. http.HandleFunc("/", handler)
  42. log.Println("Start serving on port 8089")
  43. err := http.ListenAndServe(":8089", nil)
  44. if (err!=nil) {
  45. log.Println("error:",err)
  46. }
  47. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注