Hello Go

作者: 菜鸟有个大神梦 | 来源:发表于2019-08-20 10:21 被阅读0次

    前面介绍了Web相关知识,包括HTTP协议。Go语言提供了一个完善的net/http包,通过http包可以很方便的建立一个Web服务,同时可以简单的对Web路由,静态文件,模版,cookie等数据进行设置。

    http包建立Web服务器

    在GOPATH目录下新建first_webapp子目录,并在该目录下创建server.go文件,代码如下:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
        //将“Hello World"字符串写入到ResponseWriter, 并格式化字符串,将当前请求的路径添加进去
        fmt.Fprintf(w, "Hello world, %s!", r.URL.Path[1:])
    }
    
    func main() {
        //将定义好的HelloWorldHandler函数设置成根(/)URL被访问时的处理器
        http.HandleFunc("/", HelloWorldHandler)
    
        //启动服务器并监听8000/tcp端口
        err := http.ListenAndServe(":8000", nil)
        if err != nil {
            fmt.Println(err)
        }
    }
    

    使用命令go build server.go编译上面代码, 运行编译后的文件server。或者直接go run server.go运行。
    在浏览器输入http://localhost:8000
    可以看到浏览器输出了Hello World!
    也可以换个路径试试:http://localhost:8000/index

    至此使用Go语言编写的Hello World的Web服务就完成了。
    server.go 源码连接

    相关文章

      网友评论

        本文标题:Hello Go

        本文链接:https://www.haomeiwen.com/subject/eurusctx.html