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
}