http包的使用

需求:在浏览器显示结构体各个属性的数值

package main

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

//定义结构体时,每个属性大写,不然json.Marshal会返回空字节
//但是有时候会有在前端页面显示小写的需求,这时候可以用结构体标签来解决这个问题
type Student struct {
   Name   string  `json:"name"`
   Age    int     `json:"age"`
   Height float32 `json:"height"`
}

func hello(resp http.ResponseWriter, requ *http.Request) {
   stu := Student{
      Name:   "liam",
      Age:    23,
      Height: 62.2,
   }
   result, err := json.Marshal(stu)
   if err != nil {
      fmt.Printf("json error is %s", err)
   }

   fmt.Fprintf(resp, string(result))
}

//使用内置的http库来建立web服务
func main() {
   http.HandleFunc("/index", hello)         //设置通过/index远程访问hello()
   err := http.ListenAndServe(":8090", nil) //设置端口,这样就能在浏览器输入127.0.0.1:8090/index访问hello()
   if err != nil {
      fmt.Printf("error is %s", err)
   }
}

浏览器显示:

image

posted @ 2022-09-26 15:47  雪碧锅仔饭  阅读(44)  评论(0)    收藏  举报