Loading

golang 搭建web服务器

方式一:

package main

import "net/http"

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("index page"))
	})
        println("server running at: hppt://127.0.0.1:9000")
	http.ListenAndServe(":9000", nil)
}

方式二:

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	mux.Handle("/", &index{})
	mux.HandleFunc("/demo", demo)
	println("server running at: http://127.0.0.1:9000")
	http.ListenAndServe(":9000", mux)
}

type index struct{}

func (*index) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	println(r.URL.Path)
	w.Write([]byte("index page"))
}

func demo(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("demo page"))
}

方式三

package main

import (
	"fmt"
	"net/http"
	"time"
)

func main() {
	server := http.Server{
		Addr:        ":8000",
		Handler:     &handle{},
		ReadTimeout: 5 * time.Second,
	}
	server.ListenAndServe()
}

type handle struct{}

func (*handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "home")
}

创建静态文件服务器

package main

import "net/http"

func main() {
	files := http.FileServer(http.Dir("./static/"))
	http.Handle("/file/", http.StripPrefix("/static/", files))
	http.ListenAndServe(":8000", nil)
}
posted @ 2020-08-10 14:54  fsdffsdf  阅读(250)  评论(0编辑  收藏  举报