代码改变世界

Golang net/http包服务端使用

2021-05-18 11:32  宋海宾  阅读(160)  评论(0编辑  收藏  举报

Golang的net/http提供http的服务端和客户端的http编程接口,最简单的服务端编程样例如下:

import "net/http"

func callback( w http.ResponseWriter, r *http.Request){
    str := "首页"
    w.Write([]byte(str))
}

func main() {
     http.HandleFunc("/page/index", callback)
     http.ListenAndServe("127.0.0.1:8080", nil)
}

http.HandleFunc注册全局的服务端处理程序,注册在DefaultServeMux中

返回文件的方式:

 

import "io/ioutil"

func callback(w http.ResponseWriter, r *http.Request){
   str, err := ioutil.ReadFile ("./web.html")
   if (err != nil ) {
          w.Write([]byte(str))
     }
}