首页 > 其他分享 >http包的使用

http包的使用

时间:2022-09-26 15:56:04浏览次数:46  
标签:http nil err fmt json 使用 hello

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

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

标签:http,nil,err,fmt,json,使用,hello
From: https://www.cnblogs.com/SpriteLee/p/16731195.html

相关文章

  • datafaker的使用--详细教程
    文章目录datafaker的使用一、开源情况二、工具产生背景三、软件架构四、安装流程安装对应数据库包五、使用举例5.1查看版本号,查看参数使用说明5.2......
  • 使用openpyxl读取测试数据
    --CODING:UTF-8--@Time:2022-09-2615:25@File:handle_excel**封装读取excel**fromopenpyxlimportload_workbookimportosimportjsonfromCommon.handl......
  • DDL操作数据库-修改&删除&使用和DDL操作表-查询
    DDL操作数据库-修改&删除&使用 U(Update):修改 修改数据库的字符集 alterdatabase数据库名称characterset字符集名称; D(Del......
  • 使用sphinx-book-theme构建文档
    使用sphinx-book-theme构建文档sphinx-book-themehttps://www.sphinx-doc.org/en/master/#confval-languagepipinstallsphixsphinx-book-thememyst-nb初始化构......
  • 数组使用
    数组使用数组的基本使用:packagecharpter4;​publicclassArrayDemo2{  publicstaticvoidmain(String[]args){    int[]arrays={1,2,3,4,5}; ......
  • CMake使用指南
    单文件编译添加版本号project(xxxVERSION0.1.0)指定C++版本set(CMAKE_CXX_STANDARD11)set(CMAKE_CXX_STANDARD_REQUIREDTrue)多文件编译将所有头文件放到Inc......
  • Charles for Mac(HTTP信息抓包工具)4.6.3正式版
    在上网过程中,我们有时候也会想要截留电脑软件收发的数据包用来检查网络安全,这就需要一个网络封包分析工具。CharlesMac是一款用于HTTP信息抓包工具,可以快速有效的获得HTTP......
  • Spring(十一):使用注解开发
    一、导包(添加依赖)在Spring4之后,想要使用注解就必须要导入spring-aop这个包,这里我直接添加的spring-webmvc,其中包含了我们需要的包。maven:spring-webmvc<depend......
  • 【转载】Python -- 多进程、多线程 的基本使用
    https://www.cnblogs.com/jiyu-hlzy/p/15948408.html 单进程单线程importtimedefproduction():"""间隔一秒,模拟一秒生产一个任务,生产10个任务:ret......
  • 使用 Windows 包管理器 (winget) 安装 .Net
    用户可以在Windows10和Windows11计算机上使用winget命令行工具来发现、安装、升级、删除和配置应用程序。此工具是Windows程序包管理器服务的客户端接口。......