003_go启动httpServer

一、

golang中开发http服务,可以用net/http包提供的功能。net/http包提供了非常全的功能,并且启动的http服务也非常稳定和高效,完全可以用在生产环境中。

package main

import (
    "fmt"
    "log"
    "net/http"
)

// w表示response对象,返回给客户端的内容都在对象里处理
// r表示客户端请求对象,包含了请求头,请求参数等等
func index(w http.ResponseWriter, r *http.Request) {
    // 往w里写入内容,就会在浏览器里输出
    fmt.Fprintf(w, "Hello golang http!")
}

func main() {
    // 设置路由,如果访问/,则调用index方法
    http.HandleFunc("/", index)

    // 启动web服务,监听9090端口
    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

运行服务:

go run main.go

在浏览器中访问http://localhost:8000就可以看到Hello golang http!输出了。

 

 

posted @ 2018-05-28 12:09  arun_python  阅读(473)  评论(0)    收藏  举报