golang 来自http://www.darul.io/post/2015-07-22_go-lang-simple-reverse-proxy

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 来自http://www.darul.io/post/2015-07-22_go-lang-simple-reverse-proxy相关的知识,希望对你有一定的参考价值。

package main

import (
  "fmt"
  "net"
  "os"
  "time"
)

func main() {
  service := ":55555"
  tcpAddr, err := net.ResolveTCPAddr("tcp", service)
  checkError(err)
  listner, err := net.ListenTCP("tcp", tcpAddr)
  checkError(err)
  for {
    conn, err := listner.Accept()
    if err != nil {
      continue
    }

    go handleClient(conn)
  }
}

func handleClient(conn net.Conn) {
  defer conn.Close()
  conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  fmt.Println("client accept!")
  messageBuf := make([]byte, 1024)
  messageLen, err := conn.Read(messageBuf)
  checkError(err)

  message := string(messageBuf[:messageLen])
  message = message + " too!"

  conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  conn.Write([]byte(message))
}

func checkError(err error) {
  if err != nil {
    fmt.Fprintf(os.Stderr, "fatal: error: %s", err.Error())
    os.Exit(1)
  }
}
package main

// from http://www.darul.io/post/2015-07-22_go-lang-simple-reverse-proxy

import (
  "net/http"
  "net/url"
  "net/http/httputil"
  "flag"
  "fmt"
  "regexp"
)


type Prox struct {
  target        *url.URL
  proxy         *httputil.ReverseProxy
  routePatterns []*regexp.Regexp // add some route patterns with regexp
}

func New(target string) *Prox {
  url, _ := url.Parse(target)

  return &Prox{target: url,proxy: httputil.NewSingleHostReverseProxy(url)}
}

func (p *Prox) handle(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("X-GoProxy", "GoProxy")

  if p.routePatterns == nil || p.parseWhiteList(r) {
    p.proxy.ServeHTTP(w, r)
  }
}

func (p *Prox) parseWhiteList(r *http.Request) bool {
  for _, regexp := range p.routePatterns {
    fmt.Println(r.URL.Path)
    if regexp.MatchString(r.URL.Path) {
      // let's forward it
      return true
    }
  }
  fmt.Println("Not accepted routes %x", r.URL.Path)
  return false
}


func main() {
  const (
    defaultPort             = ":80"
    defaultPortUsage        = "default server port, ':80', ':8080'..."
    defaultTarget           = "http://127.0.0.1:8080"
    defaultTargetUsage      = "default redirect url, 'http://127.0.0.1:8080'"
    defaultWhiteRoutes      = `^\/$|[\w|/]*.js|/path|/path2`
    defaultWhiteRoutesUsage = "list of white route as regexp, '/path1*,/path2*...."
  )

  // flags
  port := flag.String("port", defaultPort, defaultPortUsage)
  url := flag.String("url", defaultTarget, defaultTargetUsage)
  routesRegexp := flag.String("routes", defaultWhiteRoutes, defaultWhiteRoutesUsage)

  flag.Parse()

  fmt.Println("server will run on : %s", *port)
  fmt.Println("redirecting to :%s", *url)
  fmt.Println("accepted routes :%s", *routesRegexp)

  //
  reg, _ := regexp.Compile(*routesRegexp)
  routes := []*regexp.Regexp{reg}

  // proxy
  proxy := New(*url)
  proxy.routePatterns = routes

  // server
  http.HandleFunc("/", proxy.handle)
  http.ListenAndServe(*port, nil)
}

golang 来自HTTP API的Docker运行命令(gin-gonic)

package api

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Sdocker(c *gin.Context, image string, cmd ...string) {
	args := append([]string{"run", "--rm", image}, cmd...)
	out, err := exec.Command("docker", args...).CombinedOutput()
	if err != nil {
		c.JSON(500, gin.H{"message": err.Error()})
		return
	}
	c.String(200, string(out))
}

func JSONdocker(c *gin.Context, image string, cmd ...string) {
	args := append([]string{"run", "--rm", image}, cmd...)
	out, err := exec.Command("docker", args...).CombinedOutput()
	if err != nil {
		c.JSON(500, gin.H{"message": fmt.Sprintf("%s (%s)", err.Error(), string(out))})
		return
	}

	resp := make([]map[string]interface{}, 0)
	err = json.Unmarshal(out, &resp)
	if err != nil {
		c.JSON(500, gin.H{"message": err.Error()})
		return
	}

	c.JSON(200, resp)
}

以上是关于golang 来自http://www.darul.io/post/2015-07-22_go-lang-simple-reverse-proxy的主要内容,如果未能解决你的问题,请参考以下文章

使用来自 golang 的数据将元素添加到 html 页面

Golang 持久通道接受来自多个函数调用的输入

我如何编写处理来自 API 的响应/错误的 golang 中间件?

golang 来自HTTP API的Docker运行命令(gin-gonic)

golang 来自HTTP API的Docker运行命令(gin-gonic)

带有来自 OpenSSL 的 ECDSA 证书的 Golang HTTPS