作加速時常常須要用到 HTTP Echo Server 來測試加速有沒有成功,若是成功了,是顯示請求來自加速代理服務器。原來用 node.js 寫了一個,代碼以下: node
var http = require('http'); http.createServer( function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; var ua = req.headers['user-agent']; res.end(ip + '\n' + ua); } ).listen(80); console.log('Server is running...');
如今改成 golang,並稍微改進了一下: golang
package main import ( "fmt" "net/http" "os" "time" ) func main() { var addr string if len(os.Args) > 1 { addr = ":" + os.Args[1] } else { addr = ":80" } server := http.Server{ Addr: addr, Handler: &MyHandler{}, ReadTimeout: 5 * time.Second, } err := server.ListenAndServe() fmt.Println(err) } type MyHandler struct{} func (*MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { info := r.RemoteAddr + " @ " + time.Now().String() + "\r\n" + r.Method + " " + r.RequestURI + "\r\n" + "Host: " + r.Host + "\r\n" + "UserAgent: " + r.UserAgent() + "\r\n" w.Write([]byte(info)) fmt.Println(info) }