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
}
相关文章
|
1天前
|
存储 安全 编译器
go语言中进行不安全的类型操作
【5月更文挑战第10天】Go语言中的`unsafe`包提供了一种不安全但强大的方式来处理类型转换和底层内存操作。包含两个文档用途的类型和八个函数,本文也比较了不同变量和结构体的大小与对齐系数,强调了字段顺序对内存分配的影响。
43 8
go语言中进行不安全的类型操作
|
1天前
|
Go
配置go语言下载包 - 蓝易云
这个命令会将包下载到你的GOPATH目录下,并自动安装它。
25 1
|
2天前
|
安全 Go 调度
Go语言中的并发编程
Go语言自带了强大的并发编程能力,它的协程机制可以让程序轻松地实现高并发。本文将从并发编程的基础概念出发,介绍Go语言中的协程机制、通道和锁等相关知识点,帮助读者更好地理解并发编程在Go语言中的实践应用。
|
4天前
|
Ubuntu Unix Linux
【GO基础】1. Go语言环境搭建
【GO基础】1. Go语言环境搭建
|
5天前
|
JSON 前端开发 Go
lucky - go 语言实现的快速开发平台
go 语言实现的快速开发平台,自动生成crud代码,前端页面通过json配置,无需编写前端代码。
11 0
|
6天前
|
存储 Java Go
Go 语言切片如何扩容?(全面解析原理和过程)
Go 语言切片如何扩容?(全面解析原理和过程)
16 2
|
6天前
|
负载均衡 Go 调度
使用Go语言构建高性能的Web服务器:协程与Channel的深度解析
在追求高性能Web服务的今天,Go语言以其强大的并发性能和简洁的语法赢得了开发者的青睐。本文将深入探讨Go语言在构建高性能Web服务器方面的应用,特别是协程(goroutine)和通道(channel)这两个核心概念。我们将通过示例代码,展示如何利用协程处理并发请求,并通过通道实现协程间的通信和同步,从而构建出高效、稳定的Web服务器。
|
6天前
|
算法 Go 分布式数据库
构建高可用的分布式数据库集群:使用Go语言与Raft共识算法
随着数据量的爆炸式增长,单一数据库服务器已难以满足高可用性和可扩展性的需求。在本文中,我们将探讨如何使用Go语言结合Raft共识算法来构建一个高可用的分布式数据库集群。我们不仅会介绍Raft算法的基本原理,还会详细阐述如何利用Go语言的并发特性和网络编程能力来实现这一目标。此外,我们还将分析构建过程中可能遇到的挑战和解决方案,为读者提供一个完整的实践指南。
|
6天前
|
消息中间件 Go API
基于Go语言的微服务架构实践
随着云计算和容器化技术的兴起,微服务架构成为了现代软件开发的主流趋势。Go语言,以其高效的性能、简洁的语法和强大的并发处理能力,成为了构建微服务应用的理想选择。本文将探讨基于Go语言的微服务架构实践,包括微服务的设计原则、服务间的通信机制、以及Go语言在微服务架构中的优势和应用案例。
|
6天前
|
安全 测试技术 数据库连接
使用Go语言进行并发编程
【5月更文挑战第15天】Go语言以其简洁语法和强大的并发原语(goroutines、channels)成为并发编程的理想选择。Goroutines是轻量级线程,由Go运行时管理。Channels作为goroutine间的通信机制,确保安全的数据交换。在编写并发程序时,应遵循如通过通信共享内存、使用`sync`包同步、避免全局变量等最佳实践。理解并发与并行的区别,有效管理goroutine生命周期,并编写测试用例以确保代码的正确性,都是成功进行Go语言并发编程的关键。