GO——学习笔记(十):搭建简单的Web服务器

上篇:GO——学习笔记(九)

下篇:GO——学习笔记(十一)

参考:

https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/03.2.md

示例代码——go_9

https://github.com/jiutianbian/golang-learning/blob/master/go_9/main.go

搭建简单的Web服务器

web应用的helloworld

相对于java大部分情况需要将web程序打包成war包,然后通过tomact或者其他服务器来发布http服务不同。通过golang里面提供的完善的net/http包,可以很方便的就搭建起来一个可以运行的Web服务,无需第三方的web服务器,可以认为net/http包实现了web服务器的功能。

package main

import (
    "fmt"
    "net/http"
)

func goodgoodstudy(response http.ResponseWriter, request http.Request) {
    fmt.Println(request.URL.Path)        //request:http请求       response.Write([]byte("day day up")) //response:http响应
}

func main() {

    http.HandleFunc("/", goodgoodstudy) //设置访问的监听路径,以及处理方法

    http.ListenAndServe(":9000", nil) //设置监听的端口
}

通过浏览器访问

http://localhost:9000/

结果

《GO——学习笔记(十):搭建简单的Web服务器》 访问结果

自定义路由

查看http的源码,发现 http.HandleFunc 是默认建了一个DefaultServeMux路由来分发http请求

// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = NewServeMux()

// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

我们可以自己新建一个路由来分发请求,不用DefaultServeMux,代码如下

package main

import (
    "fmt"
    "net/http"
)

func goodgoodstudy(response http.ResponseWriter, request *http.Request) {
    fmt.Println(request.URL.Path)        //通过 request,执行http请求的相关操作
    response.Write([]byte("day day up")) //通过 response,执行http的响应相关操作
}

func nihao(response http.ResponseWriter, request *http.Request) {
    fmt.Println("nihao~~~")
    response.Write([]byte("ni hao"))
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", goodgoodstudy) //设置访问的监听路径,以及处理方法

    mux.HandleFunc("/nihao", nihao)

    http.ListenAndServe(":9000", mux) //设置监听的端口
}

通过浏览器访问

http://localhost:9000/nihao

结果

《GO——学习笔记(十):搭建简单的Web服务器》 访问结果

    原文作者:就天边
    原文地址: https://www.jianshu.com/p/1d61995988e6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞