[UMU 學 golang](5) HTTP Echo Server

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

  做加速時經常需要用到 HTTP Echo Server 來測試加速有沒有成功,如果成功了,是顯示請求來自加速Proxy 伺服器。原來用 node.js 寫了一個,代碼如下:

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,並稍微改進了一下:

package mainimport ("fmt""net/http""os""time")func main() {var addr stringif 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)}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.