创建一个go基础web服务
- 首先,创建main.go
func sayHello(w http.ResponseWriter, r *http.Request) {
b, _ := os.ReadFile("./hello.html")
_, _ = fmt.Fprintln(w, string(b))
}
func main() {
http.HandleFunc("/hello", sayHello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Println("http serve failed:", err)
return
}
}
- 再在同级目录创建hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello Golang<h1>
<p style="color:red">我是golang<p>
<button id='b1'>点我</button>
<img id="i1" src="https://inews.gtimg.com/newsapp_bt/0/13897323129/1000">
<script>
document.getElementById('b1').onclick=function(){
document.getElementById('i1').src='https://img-blog.csdnimg.cn/img_convert/481548f6364dd6ec3269ede1dd8d9220.png'
}
</script>
</body>
</html>
- 执行即可得到一个简易的golang的web服务。