Write a simple HTTP server and a static file server in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.


Package Mainimport (//"FMT" "io" "Log" "Net/http" "OS" "RegExp" "Time") Func main () {servemux: = http. Newservemux () Servemux.handlefunc ("/", SayHello) Servemux.handlefunc ("/bye", Saybye)//Servemux.handlefunc ("/static ", staticserver) Server: = http. SERVER{ADDR:        ": 8080", Handler:     servemux,readtimeout:5 * time. Second,}err: = Server. Listenandserve () if err! = Nil {log. Fatal (Err)}}func SayHello (w http. Responsewriter, R *http. Request) {If ok, _: = RegExp. Matchstring ("/static/", R.url. String ()); OK {staticserver (W, R) Return}io. WriteString (W, "Hello World")}func Saybye (w http. Responsewriter, R *http. Request) {io. WriteString (W, "Byebye")}func Staticserver (w http. Responsewriter, R *http. Request) {WD, err: = OS. GETWD () if err! = Nil {log. Fatal (Err)}http. Stripprefix ("/static/", http. Fileserver (http. Dir (WD)). Servehttp (W, R)}




http. Listenandserve (addr string, Handler handler)//Handlerhttp. Handlerinterface (servehttp)//Handler single   implements servehttp//http. Listenandserve (": 8080", single) so this//Newservemuxhttp.servemux implements servehttp//http. Listenandserve (": 8080", MUX) so you can do this//HTTP. The server contains handler, or HTTP. The defaultservemux//Defaultservemuxservemux implements servehttp//http. Listenandserve (addr string, Handler handler)//Bottom http.server//call Server. Listenandserve ()//So the last Call//Http.server structure under the Listenandserve () method//parameter addr, handler mainly for the assignment//main method handler under Servehttp side Law//responsible for general control


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.