go语言写的一个魔镜的小程序

简介: 1、利用了github上的一个go写的EventSource库;https://github.com/antage/eventsource2、利用了心知天气的api接口;https://www.seniverse.com/

WX20220918-100442.png

main.go

package main

import (
    "encoding/json"
    "fmt"
    "html/template"
    "io/ioutil"
    "net/http"
    "os"
    "os/exec"
    "runtime"
    "time"

    "example.com/pub/magicMirror/api"
)

var es = &api.Event{}

func index(w http.ResponseWriter, r *http.Request) {
    //天气预报及体感数据
    weather := new(api.Result)
    weather.AddResult()
    //今天
    toDay := time.Now().Format("2006-01-02 15:04")
    fmt.Println(toDay, "刷新")
    //模板
    var template = template.Must(template.ParseGlob("client/templates/*"))
    template.ExecuteTemplate(w, "index.html", weather)
}

//添加课程表后台
func createCourse(w http.ResponseWriter, r *http.Request) {
    var template = template.Must(template.ParseGlob("client/templates/*"))
    template.ExecuteTemplate(w, "addCourse.html", nil)
}

//生成课程表后台的json数据
func seekCourse(w http.ResponseWriter, r *http.Request) {
    var monday = r.FormValue("monday")
    var mondaySlice = r.FormValue("mondaySlice")
    var tuesday = r.FormValue("tuesday")
    var tuesdaySlice = r.FormValue("tuesdaySlice")
    var wednesday = r.FormValue("wednesday")
    var wednesdaySlice = r.FormValue("wednesdaySlice")
    var friday = r.FormValue("friday")
    var fridaySlice = r.FormValue("fridaySlice")
    var saturday = r.FormValue("saturday")
    var saturdaySlice = r.FormValue("saturdaySlice")
    var sunday = r.FormValue("sunday")
    var sundaySlice = r.FormValue("sundaySlice")
    if monday == "" || tuesday == "" || wednesday == "" || friday == "" || saturday == "" || sunday == "" {
        fp, _ := os.Open("interface/courseJson.json")
        dummy, _ := ioutil.ReadAll(fp)
        w.Write(dummy)
    } else {
        var cu = new(api.Calender)
        cu.AddMsg(monday, mondaySlice)
        cu.AddMsg(tuesday, tuesdaySlice)
        cu.AddMsg(wednesday, wednesdaySlice)
        cu.AddMsg(friday, fridaySlice)
        cu.AddMsg(saturday, saturdaySlice)
        cu.AddMsg(sunday, sundaySlice)
        fmt.Println(len(cu.Items.Items))
        cu.CreateCourseJson()
        dummy := cu.Read()
        w.Write([]byte(dummy))
    }

}

//添加事件通知
func createEvent(w http.ResponseWriter, r *http.Request) {
    tpl := template.Must(template.ParseGlob("client/templates/*"))
    tpl.ExecuteTemplate(w, "createEvent.html", nil)
    if r.FormValue("event") != "" {
        msg := r.FormValue("event")
        go func(msg string) {
            es.Ev.SendEventMessage(msg, "", "")
        }(msg)
        w.Write([]byte(fmt.Sprintf("%s事件添加完毕", msg)))
    }
}

//天气预报
func weather(w http.ResponseWriter, r *http.Request) {
    weather := new(api.Weather)
    weather.CreateWeather("yingkou")
    tpl := template.Must(template.ParseGlob("client/templates/*"))
    tpl.ExecuteTemplate(w, "weather.html", weather.Results[0])
    dummy, _ := json.Marshal(&weather)
    w.Write([]byte(dummy))
}
func NewRoute() *http.ServeMux {
    r := http.NewServeMux()
    //静态数据
    r.Handle("/favicon.ico", http.NotFoundHandler())
    r.Handle("/client/css/", http.StripPrefix("/client/css", http.FileServer(http.Dir("client/css"))))
    r.Handle("/client/img/", http.StripPrefix("/client/img", http.FileServer(http.Dir("client/img"))))
    r.Handle("/client/js/", http.StripPrefix("/client/js", http.FileServer(http.Dir("client/js"))))
    //首页
    r.HandleFunc("/", index)
    //后台课程表添加数据
    r.HandleFunc("/createcourse", createCourse)
    //处理生成课程表
    r.HandleFunc("/course", seekCourse)
    //处理通知事件
    r.Handle("/event", es.Ev)
    r.HandleFunc("/createEvent", createEvent)
    //天气预报
    r.HandleFunc("/weather", weather)
    return r
}

func open(url string) error {
    var (
        cmd  string
        args []string
    )

    switch runtime.GOOS {
    case "windows":
        cmd, args = "cmd", []string{"/c", "start"}
    case "darwin":
        cmd = "open"
    default:
        // "linux", "freebsd", "openbsd", "netbsd"
        cmd = "xdg-open"
    }
    args = append(args, url)
    return exec.Command(cmd, args...).Start()
}
func main() {
    es.Init()
    defer es.Ev.Close()
    mux := NewRoute()
    fmt.Println("魔镜启动中......")
    open("http://localhost")
    http.ListenAndServe(":80", mux)
}

api/weather.go

package api

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

type Weather struct {
    Results []weatherLocation `json:"results"`
}
type weatherLocation struct {
    Location location `json:"location"`
    Now      now      `json:"now"`
}
type location struct {
    Id              string `json:"id"`
    Name            string `json:"name"`
    Country         string `json:"country"`
    Path            string `json:"path"`
    Timezone        string `json:"timezone"`
    Timezone_offset string `json:"timezone_offset"`
}
type now struct {
    Text        string `json:"text"`
    Code        string `json:"code"`
    Temperature string `json:"temperature"`
}

func (w *Weather) CreateWeather(city string) {
    key := "xxxxxxxxxxxxxxxxx"
    var url = fmt.Sprintf("https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c", key, city)
    response, err := http.DefaultClient.Get(url)
    if err != nil {
        log.Fatal("天气url打开错误", err)
        return
    }
    defer response.Body.Close()
    data, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal("天气预报解析错误", err)
        return
    }
    json.Unmarshal(data, &w)
}

api/result.go

package api

type Result struct {
    //城市名
    City string
    //天气图标序号
    WeatherIcon string
    //天气状态如:多云
    Text string
    //气温
    Temperature string
    //体感舒适度
    Life string
    //紫外线
    Uv string
    //穿衣
    Dressing string
    //运动
    Sport string
    //感冒
    Flu string
    //历史上的今天
    HistoryDate  string
    HistoryTitle string
}

func (r *Result) AddResult() {
    var ws = new(Weather)
    ws.CreateWeather("yingkou")
    r.City = ws.Results[0].Location.Name
    r.WeatherIcon = ws.Results[0].Now.Code
    r.Text = ws.Results[0].Now.Text
    r.Temperature = ws.Results[0].Now.Temperature
    //体感
    var lf = new(Life)
    lf.CreateLife("yingkou")
    r.Life = lf.Results[0].Suggestion[0].Comfort.Details
    //紫外线
    r.Uv = lf.Results[0].Suggestion[0].Uv.Brief
    //穿衣
    r.Dressing = lf.Results[0].Suggestion[0].Dressing.Brief
    //运动
    r.Sport = lf.Results[0].Suggestion[0].Sport.Brief
    //感冒
    r.Flu = lf.Results[0].Suggestion[0].Flu.Brief
    //历史上的今天
    var hi = new(History)
    hi.Add()
    r.HistoryDate = hi.Result[1].Date
    r.HistoryTitle = hi.Result[1].Title
}
相关文章
|
17小时前
|
JSON 安全 Java
2024年的选择:为什么Go可能是理想的后端语言
【4月更文挑战第27天】Go语言在2024年成为后端开发的热门选择,其简洁设计、内置并发原语和强大工具链备受青睐。文章探讨了Go的设计哲学,如静态类型、垃圾回收和CSP并发模型,并介绍了使用Gin和Echo框架构建Web服务。Go的并发通过goroutines和channels实现,静态类型确保代码稳定性和安全性,快速编译速度利于迭代。Go广泛应用在云计算、微服务等领域,拥有丰富的生态系统和活跃社区,适合作为应对未来技术趋势的语言。
8 0
|
19小时前
|
安全 测试技术 Go
Golang深入浅出之-Go语言单元测试与基准测试:testing包详解
【4月更文挑战第27天】Go语言的`testing`包是单元测试和基准测试的核心,简化了测试流程并鼓励编写高质量测试代码。本文介绍了测试文件命名规范、常用断言方法,以及如何进行基准测试。同时,讨论了测试中常见的问题,如状态干扰、并发同步、依赖外部服务和测试覆盖率低,并提出了相应的避免策略,包括使用`t.Cleanup`、`t.Parallel()`、模拟对象和检查覆盖率。良好的测试实践能提升代码质量和项目稳定性。
6 1
|
19小时前
|
运维 监控 Go
Golang深入浅出之-Go语言中的日志记录:log与logrus库
【4月更文挑战第27天】本文比较了Go语言中标准库`log`与第三方库`logrus`的日志功能。`log`简单但不支持日志级别配置和多样化格式,而`logrus`提供更丰富的功能,如日志级别控制、自定义格式和钩子。文章指出了使用`logrus`时可能遇到的问题,如全局logger滥用、日志级别设置不当和过度依赖字段,并给出了避免错误的建议,强调理解日志级别、合理利用结构化日志、模块化日志管理和定期审查日志配置的重要性。通过这些实践,开发者能提高应用监控和故障排查能力。
8 1
|
19小时前
|
安全 Go
Golang深入浅出之-Go语言标准库中的文件读写:io/ioutil包
【4月更文挑战第27天】Go语言的`io/ioutil`包提供简单文件读写,适合小文件操作。本文聚焦`ReadFile`和`WriteFile`函数,讨论错误处理、文件权限、大文件处理和编码问题。避免错误的关键在于检查错误、设置合适权限、采用流式读写及处理编码。遵循这些最佳实践能提升代码稳定性。
5 0
|
21小时前
|
Go C++
go 语言回调函数和闭包
go 语言回调函数和闭包
|
1天前
|
存储 负载均衡 监控
【Go 语言专栏】构建高可靠性的 Go 语言服务架构
【4月更文挑战第30天】本文探讨了如何利用Go语言构建高可靠性的服务架构。Go语言凭借其高效、简洁和并发性能,在构建服务架构中备受青睐。关键要素包括负载均衡、容错机制、监控预警、数据存储和服务治理。文章详细阐述了实现这些要素的具体步骤,通过实际案例分析和应对挑战的策略,强调了Go语言在构建稳定服务中的作用,旨在为开发者提供指导。
|
1天前
|
测试技术 Go 开发工具
【Go语言专栏】Go语言中的代码审查与最佳实践
【4月更文挑战第30天】Go语言因其简洁、高性能及并发能力,在云计算等领域广泛应用。代码审查对提升Go代码质量、遵循规范及团队协作至关重要。审查流程包括提交、审查、反馈、修改和合并代码。工具如GoLand、Git、ReviewBoard和GitHub提供支持。最佳实践包括遵循命名规范、添加注释、保持代码结构清晰、复用代码和确保测试覆盖。积极参与代码审查是提高质量的关键。
|
1天前
|
Prometheus 监控 Cloud Native
【Go语言专栏】Go语言中的日志记录与监控
【4月更文挑战第30天】Go语言在软件开发和运维中扮演重要角色,提供灵活的日志记录机制和与多种监控工具的集成。内置`log`包支持基本日志记录,而第三方库如`zap`、`zerolog`和`logrus`则扩展了更多功能。监控方面,Go应用可与Prometheus、Grafana、Jaeger等工具配合,实现系统指标收集、可视化和分布式追踪。健康检查通过HTTP端点确保服务可用性。结合日志和监控,能有效提升Go应用的稳定性和性能。
|
1天前
|
存储 安全 中间件
【Go语言专栏】Go语言中的安全认证与授权机制
【4月更文挑战第30天】本文探讨了Go语言中实现安全认证与授权的方法。认证机制包括HTTP Basic Auth、表单认证、OAuth和JWT,可借助`net/http`及第三方库实现。授权则通过中间件或拦截器,如RBAC、ABAC和上下文相关授权,`casbin`和`go-permission`等库提供解决方案。实践中,需设计认证流程、存储用户凭证、实现逻辑、定义授权策略和编写中间件,并确保安全性。案例分析展示了认证授权在RESTful API服务中的应用。在Go开发中,不断学习和优化安全策略以应对安全挑战至关重要。
|
1天前
|
SQL 安全 Go
【Go语言专栏】Go语言中的安全审计与漏洞修复
【4月更文挑战第30天】本文介绍了Go语言中的安全审计和漏洞修复实践。安全审计包括代码审查、静态分析、运行时分析、渗透测试和专业服务,借助工具如`go vet`、`staticcheck`、`gosec`等。修复漏洞的方法涉及防止SQL注入、XSS攻击、CSRF、不安全反序列化等。遵循最小权限原则、输入验证等最佳实践,结合持续学习,可提升Go应用安全性。参考[Go安全工作组](https://github.com/golang/security)和[OWASP Top 10](https://owasp.org/www-project-top-ten/)深入学习。