Golang如何将输出结果转换为HTML表格格式

Golang如何将输出结果转换为HTML表格格式

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"strings"
	"net/http"
)

func Handle(w http.ResponseWriter,r *http.Request) {
	const jsonStream=  `{"id": 1, "Name": "John", "Salary": 6000} 				 {"id": 2, "Name": "Mark", "Salary": 7000} 				 {"id": 3, "Name": "Sandy", "Salary": 8000} 				 {"id": 4, "Name": "Holard","Salary": 2000}`
	type Employee struct {
		id int      `json:"id"`
		Name string `json:"name"`
		Salary int  `json:"salary"`
	}

	dec := json.NewDecoder(strings.NewReader(jsonStream))
	for {
		var emp Employee
		if err := dec.Decode(&emp); err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}
		if emp.Salary>5000{
			fmt.Fprintf(w," %d  %s  %d ",emp.id,emp.Name,emp.Salary)
		}
	}
}

func main(){
	http.HandleFunc("/",Handle)
	http.ListenAndServe(":8081",nil)
}

更多关于Golang如何将输出结果转换为HTML表格格式的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

为什么我在上面的程序中,在指定 %d 的位置得到了零值? 有什么建议吗?

更多关于Golang如何将输出结果转换为HTML表格格式的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


id 不是公开字段,因此对 reflection 包不可见,该包被 json(反)序列化器用于检查结构体。

所有需要在 JSON 中使用的字段都必须是公开的(以大写字母开头)。

代码的可读版本可在以下链接找到:https://play.golang.org/p/QdV7OhQPLg2

要实现你的目标,有几种选择:

  1. 使用 html/template
  2. 在进入循环前将表头写入流,在循环中将列数据写入流,循环结束后再写入表尾

编辑说明

第一种解决方案需要更多工作,因为你需要学习模板语言,同时还需要创建合适的工作上下文。但从长远来看,这将使代码更易读、更简洁,并且更易于维护。

以下是针对将输出结果转换为HTML表格格式的修改方案。原代码存在几个问题:JSON流格式不正确(缺少逗号分隔和数组括号),结构体字段需要导出(首字母大写),以及需要生成HTML表格而非纯文本输出。

package main

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

func Handle(w http.ResponseWriter, r *http.Request) {
	const jsonStream = `[
		{"id": 1, "Name": "John", "Salary": 6000},
		{"id": 2, "Name": "Mark", "Salary": 7000},
		{"id": 3, "Name": "Sandy", "Salary": 8000},
		{"id": 4, "Name": "Holard", "Salary": 2000}
	]`
	
	type Employee struct {
		ID     int    `json:"id"`
		Name   string `json:"Name"`
		Salary int    `json:"Salary"`
	}

	var employees []Employee
	err := json.Unmarshal([]byte(jsonStream), &employees)
	if err != nil {
		http.Error(w, "Error parsing JSON", http.StatusInternalServerError)
		log.Printf("JSON parse error: %v", err)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	
	// 开始HTML表格
	fmt.Fprint(w, `<table border="1">
		<tr>
			<th>ID</th>
			<th>Name</th>
			<th>Salary</th>
		</tr>`)

	for _, emp := range employees {
		if emp.Salary > 5000 {
			fmt.Fprintf(w, `<tr>
				<td>%d</td>
				<td>%s</td>
				<td>%d</td>
			</tr>`, emp.ID, emp.Name, emp.Salary)
		}
	}
	
	fmt.Fprint(w, "</table>")
}

func main() {
	http.HandleFunc("/", Handle)
	log.Println("Server starting on :8081")
	log.Fatal(http.ListenAndServe(":8081", nil))
}

主要修改点:

  1. 将JSON流改为标准JSON数组格式
  2. 结构体字段改为导出字段(首字母大写)并修正JSON标签
  3. 使用json.Unmarshal一次性解析JSON数组
  4. 设置响应头为HTML内容类型
  5. 输出完整的HTML表格结构,包含表头和表格行
  6. 保留薪资大于5000的过滤条件

访问 http://localhost:8081 将会看到格式化的HTML表格显示符合条件的员工数据。

回到顶部