Skip to content

Commit

Permalink
JSON return.
Browse files Browse the repository at this point in the history
  • Loading branch information
icemarkom committed Sep 6, 2020
1 parent 0cc1965 commit fafe684
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions pitemp.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
Expand All @@ -20,6 +21,11 @@ type Config struct {
Port int
}

// JSONReturn holds the values for JSON printout.
type JSONReturn struct {
Temperature int `json:"temperature"`
}

var cfg Config

func init() {
Expand All @@ -43,16 +49,29 @@ func readTemperature() (int, error) {
}

func handleRoot(w http.ResponseWriter, r *http.Request) {
var (
j JSONReturn
err error
)

if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
t, err := readTemperature()
j.Temperature, err = readTemperature()
if err != nil {
log.Printf("Could not read temperature: %v.\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
jr, err := json.Marshal(j)
if err != nil {
log.Printf("Could not generate JSON response: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
fmt.Fprintln(w, t)
log.Print(jr)
fmt.Fprintln(w, string(jr))
}

func main() {
Expand Down

0 comments on commit fafe684

Please sign in to comment.