Go http库创建Web项目-http库的简单使用

1、创建一个简单web程序只需要简单的两个步骤即可

  • 通过http.ListenAndServe()监听端口

  • 通过http.HandleFunc()注册路由且绑定响应事件

package main

import (
   "fmt"
   "net/http"
)

func helloWorld(w http.ResponseWriter,r *http.Request)  {
   fmt.Println("hello world")
}
func main() {
   http.HandleFunc("/",helloWorld)
   err := http.ListenAndServe(":8080", nil)
   if err!=nil{
      panic("启动服务失败")
   }
}

运行程序,用浏览器打开 http://localhost:8080/ 即可访问。

此时页面上没有任何输出,但是能看到控制台上打印了hello world,这样就表示用户访问http://localhost:8080/网址,可以进入到我们的函数里了。

运行结果:

image-20220509210953301

打印两次hello world请别慌,因为访问http://localhost:8080/时,会自动访问http://localhost:8080/favicon.ico,如果你打印了r变量,你就会看到类似如下截图效果,这就是为什么打印了两次hello world的原因

image-20220509211501996

2、返回数据给前端

  • 调用w.Write()返回数据(因为Write函数只接受byte数组,因此构建一个byte数组即可)
package main

import (
   "encoding/json"
   "fmt"
   "net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
   fmt.Println(fmt.Sprintf("请求的参数:%+v", r))
   fmt.Println("hello world")

   //定义返回的json
   resp := make(map[string]interface{})
   resp["data"] = "hello world"
   resp["msg"] = ""
   resp["success"] = true
   bytes, _ := json.Marshal(resp)

   w.Write(bytes)
}
func main() {
   http.HandleFunc("/data", helloWorld)
   err := http.ListenAndServe(":8080", nil)
   if err != nil {
      panic("启动服务失败")
   }
}

由于不想多次调用函数,也就是不想前端自动请求/favicon.ico,因此改动一下路由,请求就变成了http://localhost:8080/data

运行

image-20220509213505209

3、通过结构体返回数据

上面的例子都是通过函数的形式来进行返回前端,可是Go经常会定义一些结构体,有没有一种使用结构体的形式来完成上面的功能呢?答案是有点,只需要以下几步

  • 定义一个结构体

  • 结构体实现方法名为ServeHTTP且参数为(w http.ResponseWriter, r *http.Request)的方法

  • 使用http.Handle()注册路由且绑定响应事件

package main

import (
   "encoding/json"
   "fmt"
   "net/http"
)

type ClassInfo struct {
   ClassName string `json:"class_name"`
   ClassId   int    `json:"class_id"`
}

func (receiver ClassInfo) ShowClassInfo()  []byte{
   //打印班级的信息
   fmt.Println(fmt.Sprintf("班级ID:%d 班级名称:%s",receiver.ClassId,receiver.ClassName))
   bytes, _ := json.Marshal(receiver)
   fmt.Println(fmt.Sprintf("%s",bytes))
   return bytes
}

func (receiver ClassInfo) ServeHTTP(w http.ResponseWriter, r *http.Request)  {
   //返回班级信息给前端
   w.Write(receiver.ShowClassInfo())
}

func main() {
   classInfo := ClassInfo{
      ClassName: "一年级五班",
      ClassId:   10086,
   }
   http.Handle("/data",&classInfo)
   http.ListenAndServe(":8080",nil)
}

运行,访问http://localhost:8080/data

image-20220509214921382

3.1、为什么这么定义呢?

因为从源代码可以看到http.HandleFunc()和http.Handle()都可以注册路由,最终都是通过DefaultServeMux.HandleFunc(pattern, handler)来完成的。

image-20220509215331393

而http.Handle()需要传递一个叫Handler的参数,再点进去看看,原来这是一个接口

image-20220509215526189

因此只要实现这个接口的这个方法就行了,这也就是我们要类实现的那个方法!

待续...

posted @ 2022-05-09 22:01  南风丶轻语  阅读(90)  评论(0编辑  收藏  举报