Hello World con Golang (helloworld.go):
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
Webservice, API Rest y MongoDB (Mgo) con Golang (test.go):
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Modelo para manejar los datos con mongodb
type Person struct {
Id string
Name string
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/addPerson/{name}/{id}", addPerson).Methods("GET")
router.HandleFunc("/getPerson/{name}", getPerson).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", router))
}
func addPerson(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
id := vars["id"]
// Insercion en mongo
session, err := mgo.Dial("mongodb://localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("testgo").C("people")
err = c.Insert(&Person{id, name})
if err != nil {
log.Fatal(err)
}
}
func getPerson(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
// Consulta en mongo
session, err := mgo.Dial("mongodb://localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("testgo").C("people")
result := Person{}
err = c.Find(bson.M{"name": name}).One(&result)
if err != nil {
log.Fatal("error: ", err)
}
fmt.Println("id:", result.Id, " - name:",result.Name)
}
Código .ino para NodeMCU con Node-Red y MQTT
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "xxxxxxxxxx"; // cannot be longer than 32 characters!
const char *pass = "yyyyyyyyyy"; //
// Update these with values suitable for your network.
IPAddress server(192, 168, 1, 50);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.println("event");
}
WiFiClient wclient;
PubSubClient client(wclient, server);
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
client.set_callback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (client.connect("nodeMCUClient")) {
client.publish("ourtopic","hello world");
client.subscribe("thetopic");
}
}
if (client.connected())
client.loop();
}
}