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
}
相关文章
|
11天前
|
程序员 Go PHP
为什么大部分的 PHP 程序员转不了 Go 语言?
【9月更文挑战第8天】大部分 PHP 程序员难以转向 Go 语言,主要因为:一、编程习惯与思维方式差异,如语法风格和编程范式;二、学习成本高,需掌握新知识体系且面临项目压力;三、职业发展考量,现有技能价值及市场需求不确定性。学习新语言虽有挑战,但对拓宽职业道路至关重要。
42 10
|
9天前
|
Go API 开发者
深入探讨:使用Go语言构建高性能RESTful API服务
在本文中,我们将探索Go语言在构建高效、可靠的RESTful API服务中的独特优势。通过实际案例分析,我们将展示Go如何通过其并发模型、简洁的语法和内置的http包,成为现代后端服务开发的有力工具。
|
11天前
|
算法 程序员 Go
PHP 程序员学会了 Go 语言就能唬住面试官吗?
【9月更文挑战第8天】学会Go语言可提升PHP程序员的面试印象,但不足以 solely “唬住” 面试官。学习新语言能展现学习能力、拓宽技术视野,并增加就业机会。然而,实际项目经验、深入理解语言特性和综合能力更为关键。全面展示这些方面才能真正提升面试成功率。
35 10
|
11天前
|
编译器 Go
go语言学习记录(关于一些奇怪的疑问)有别于其他编程语言
本文探讨了Go语言中的常量概念,特别是特殊常量iota的使用方法及其自动递增特性。同时,文中还提到了在声明常量时,后续常量可沿用前一个值的特点,以及在遍历map时可能遇到的非顺序打印问题。
|
8天前
|
存储 监控 数据可视化
Go 语言打造公司监控电脑的思路
在现代企业管理中,监控公司电脑系统对保障信息安全和提升工作效率至关重要。Go 语言凭借其高效性和简洁性,成为构建监控系统的理想选择。本文介绍了使用 Go 语言监控系统资源(如 CPU、内存)和网络活动的方法,并探讨了整合监控数据、设置告警机制及构建可视化界面的策略,以满足企业需求。
25 1
|
15天前
|
安全 大数据 Go
深入探索Go语言并发编程:Goroutines与Channels的实战应用
在当今高性能、高并发的应用需求下,Go语言以其独特的并发模型——Goroutines和Channels,成为了众多开发者眼中的璀璨明星。本文不仅阐述了Goroutines作为轻量级线程的优势,还深入剖析了Channels作为Goroutines间通信的桥梁,如何优雅地解决并发编程中的复杂问题。通过实战案例,我们将展示如何利用这些特性构建高效、可扩展的并发系统,同时探讨并发编程中常见的陷阱与最佳实践,为读者打开Go语言并发编程的广阔视野。
|
12天前
|
存储 Shell Go
Go语言结构体和元组全面解析
Go语言结构体和元组全面解析
|
17天前
|
Go
golang语言之go常用命令
这篇文章列出了常用的Go语言命令,如`go run`、`go install`、`go build`、`go help`、`go get`、`go mod`、`go test`、`go tool`、`go vet`、`go fmt`、`go doc`、`go version`和`go env`,以及它们的基本用法和功能。
26 6
|
17天前
|
存储 Go
Golang语言基于go module方式管理包(package)
这篇文章详细介绍了Golang语言中基于go module方式管理包(package)的方法,包括Go Modules的发展历史、go module的介绍、常用命令和操作步骤,并通过代码示例展示了如何初始化项目、引入第三方包、组织代码结构以及运行测试。
19 3
|
2天前
|
Shell Go API
Go语言grequests库并发请求的实战案例
Go语言grequests库并发请求的实战案例