本示例实现了http请求获取html页面:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"unsafe"
)
func main() {
http.HandleFunc("/", sendHTML)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe:", err.Error())
}
}
func loadHTML(filename string) ([]byte, error) {
filename += ".html"
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return content, nil
}
func sendHTML(writer http.ResponseWriter, request *http.Request) {
loadHTML("index")
html, err := loadHTML("index")
if err != nil {
fmt.Printf("ERROR:", err.Error())
} else {
fmt.Fprint(writer, *(*string)(unsafe.Pointer(&html)))
}
}
编译程序,在程序所在目录创建index.html文件,在html文件中写入需要显示的页面,然后打开运行程序,打开浏览器,输入http://127.0.0.1:8080,可以看到成功打开了html页面。