tips:
This is probably the easiest web backend development demo
Create a main.go in goland and follow the instructions of the http package to write the code as follows:
package main
import (
"fmt"
"net/http"
)
func sayhello(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, "<h1>hey this is LIBERHOME!</h1>")
}
func main() {
http.HandleFunc("/hello", sayhello)
err := http.ListenAndServe(":9090", nil) //服务器启动后,监听9090端口
if err != nil {
fmt.Printf("http service failed, err: %v\n", err)
return
}
}
Then execute it in the terminal
go run main.go
Then type in the browser
http://127.0.0.1:9090/hello
to see
Of course, directly hardcoding the content displayed on the web page can be changed to a txt file:
First create a hello.txt:
<h1>hey it is LIBERHOME!</h1>
<h2>this may be the most simple demo~</h2>
<img id='i1' src='https://avatar-static.segmentfault.com/274/037/2740371703-61baf9dec42e4_huge256'>
Then the previous code is slightly modified and added to the ioutil package:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func sayhello(w http.ResponseWriter, r *http.Request) {
b, _ := ioutil.ReadFile("./hello.txt")
_, _ = fmt.Fprint(w, string(b))
}
func main() {
http.HandleFunc("/hello", sayhello)
err := http.ListenAndServe(":9090", nil) //服务器启动后, 监听9090端口
if err != nil {
fmt.Printf("http service failed, err: %v\n", err)
return
}
}
The results are as follows:
Reference: bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。