Skip to content

Instantly share code, notes, and snippets.

@Ynn
Created November 7, 2017 19:34
Show Gist options
  • Save Ynn/b00440d3156c975cf13a4581dff8b0ed to your computer and use it in GitHub Desktop.
Save Ynn/b00440d3156c975cf13a4581dff8b0ed to your computer and use it in GitHub Desktop.
example curl -l http://localhost:8080/example.com/obix/org/lon/@XBureau922/@XLocations/@XLSI/@XSunSensor/@XnvoSunLux_2/$@CSNVT_lux/?name=lux2&format=influx
package main
import (
"fmt"
"io/ioutil"
"net/http"
"encoding/xml"
"strconv"
"time"
)
type ObixValue struct {
XMLName xml.Name
Value string `xml:"val,attr"`
}
func handler(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get("http://" + r.URL.Path[1:])
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
v := ObixValue{}
err = xml.Unmarshal(body, &v)
if err != nil {
return
}
switch(r.URL.Query().Get("format")){
case "influx":
w.Header().Set("Content-type","text/plain")
timestamp := time.Now().UnixNano()
switch v.XMLName.Local {
case "int":
if value, err := strconv.Atoi(v.Value); err == nil {
fmt.Fprintf(w, "obix %s=%d %d",r.URL.Query().Get("name"),value, timestamp )
}
case "real":
if value, err := strconv.ParseFloat(v.Value,64); err == nil {
fmt.Fprintf(w, "obix %s=%f %d",r.URL.Query().Get("name"),value,timestamp )
}
default:
fmt.Fprintf(w, "obix %s=%s %d",r.URL.Query().Get("name"),v.Value,timestamp )
}
case "text":
w.Header().Set("Content-type","text/plain")
fmt.Fprintf(w, "%s",v.Value )
default:
w.Header().Set("Content-type","application/json")
switch v.XMLName.Local {
case "int":
if value, err := strconv.Atoi(v.Value); err == nil {
fmt.Fprintf(w, "{\"%s\" : %d}",r.URL.Query().Get("name"),value )
}
case "real":
if value, err := strconv.ParseFloat(v.Value,64); err == nil {
fmt.Fprintf(w, "{\"%s\" : %f}",r.URL.Query().Get("name"),value )
}
default:
fmt.Fprintf(w, "{\"%s\" : \"%s\"}",r.URL.Query().Get("name"),v.Value )
}
}
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment