关于gin:Go-nethttp-以及ioioutil包的使用

4次阅读

共计 990 个字符,预计需要花费 3 分钟才能阅读完成。

tips:
这可能是最繁难的 web 后端开发 demo

在 goland 中创立一个 main.go 而后依照 http 包的应用阐明编写代码如下:

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
    }
}

接下来在 terminal 执行
go run main.go
而后在浏览器输出
http://127.0.0.1:9090/hello
即可看到


当然,间接把网页显示的内容硬编码能够改成一个 txt 文件的形式:
首先创立一个 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'>

而后之前的代码稍加批改, 退出 ioutil 包:

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
    }
}

运行后果如下:

参考:bilibili

正文完
 0