文章目录
本文章是为了解决 使用Jenkins执行TestNg+Selenium+Jsoup自动化测试和生成ExtentReport测试报告生成的测试报告,只能在jenkins里面访问,为了方便项目组内所有人员都能查看测试报,可以在jenkins构建时,把测试报告的html推送到其它http服务,再让该http服务提供访问。
为了实现上边的功能,需要编写两个HTTP接口:
- 1、upload接口,接收发送的html内容,并保存到硬盘中。
- 2、view接口,提供浏览html文件服务。
本文使用Go的Gin框架实现上述功能,
package mainimport ("bufio""crypto/md5""encoding/hex""encoding/json""github.com/gin-gonic/gin"uuid "github.com/satori/go.uuid""io""log""net/http""os""strings""time"
)type WebData struct {Content string `json:"content"`//Token string `json:"token_key"`
}
type ViewData struct {Date string `uri:"date" binding:"required"`Hour string `uri:"hour" binding:"required"`Path string `uri:"path" binding:"required"`
}func readString(name string) string {file, err := os.Open(name)if err != nil {panic(err)}var content = ""r := bufio.NewReader(file)for {line, err := r.ReadString('\n')if err != nil && err != io.EOF {panic(err)}line = strings.TrimSpace(line)content += lineif err == io.EOF {break}content += "\n"}file.Close()return content
}
func writeString(name string, content string) int {file, err := os.Create(name)if err != nil {panic(err)}w := bufio.NewWriter(file)len, err2 := w.WriteString(content)if err2 == nil {w.Flush()}file.Close()return len
}/*
*
本文不使用
*/
func md5Str(str string) (encode string) {md5 := md5.New()md5.Write([]byte(str))return hex.EncodeToString(md5.Sum(nil))
}
func upload(c *gin.Context) {result := gin.H{"url": "",}data := WebData{}requestBody, err := c.GetRawData()if err == nil {err2 := json.Unmarshal(requestBody, &data)if err2 == nil {date := time.Now().Format("20060102/15/")log.Printf("date====%v", date)u1 := uuid.NewV4()log.Printf("uuid====%v", u1.String())path := "temp/" + datefile := u1.String() + ".html"name := path + filelog.Printf("path====%v", name)_, err := os.Stat(path)if err != nil || os.IsNotExist(err) {os.MkdirAll(path, 0755)}content := data.Contentlen := writeString(name, content)log.Printf("writeString====%v", len)result["url"] = server + "/view/" + date + file} else {log.Println(err2)}}c.JSON(http.StatusOK, gin.H{"data": result,})
}
func view(c *gin.Context) {var viewData ViewDataif err := c.ShouldBindUri(&viewData); err != nil {c.String(400, err.Error())return}log.Printf("===date:%v,hour:%v,path:%v", viewData.Date, viewData.Hour, viewData.Path)name := "temp/" + viewData.Date + "/" + viewData.Hour + "/" + viewData.Pathc.Header("Content-Type", "text/html;charset=utf-8")conetnt := readString(name)log.Printf("view =====content:%v", conetnt)c.String(http.StatusOK, conetnt)
}const server string = "http://localhost:8080/html"func main() {router := gin.Default()router.Static("/temp", "./temp")v1 := router.Group("/html"){v1.POST("/upload", upload)v1.GET("/view/:date/:hour/:path", view)}// 监听并在 0.0.0.0:8080 上启动服务router.Run(":8080")
}
后期优化可以添加安全验证功能。
运行效果
访问upload接口,
通过view接口访问页面