This is a creation in Article, where the information may have evolved or changed.
This is just a record of your own learning process.
First, you need to introduce the "Net/http" package
import "net/http"
After importing the related package, the next step is to initialize it in the main function, and a few lines of code will build the good one HTTP server
err := http.ListenAndServe(":8080", nil)if err != nil {fmt.Println("服务启动失败。")}
Above just set up a service, and there is no function, below I also want to add the corresponding handlefunc so that can respond to related requests. As follows:
First, set up a Handlefunc callback function
func homeHandler(w http.ResponseWriter, h *http.Request) {w.Write([]byte("hello ying32!"))}
Then initially bind in the main function, remember to be sure to do so in http. Listenandserve before binding, here I bind the root directory "/", when access to Local: http://127.0.0.1:8080 can be called to the Homehandler function.
http.HandleFunc("/", homeHandler)
Alternatively, you can use http. Fileserver to quickly bind a directory as a static file service.
http.Handle("/static", http.FileServer(http.Dir("你的目录")))