package main
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/google/uuid"
"github.com/spf13/viper"
)
var (
db *sql.DB
err error
)
func main() {
fmt.Println("Starting Soil Sensor API")
// reading config file
fmt.Println("Reading config file")
// get variables from config
username := viper.GetString("dbusername")
password := viper.GetString("dbpassword")
address := viper.GetString("dbaddress")
port := viper.GetInt("dbport")
dbName := viper.GetString("dbname")
// connect to database
fmt.Printf("Establishing connection to MySQL server: %s:%d\n", address, port)
db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", username, password, address, port, dbName))
if err != nil {
fmt.Printf("Establishing to mysql server error: %v\n", err)
os.Exit(1)
}
fmt.Println("MySQL server successfully connected")
fmt.Println("Started http api server")
// setup http server
http.HandleFunc("/create", handleDataReceivedRequest)
// start listening http request
err := http.ListenAndServe(fmt.Sprintf(":%d", viper.GetInt("httpport")), nil)
if err != nil {
fmt.Printf("Listening http request error: %v\n", err)
os.Exit(1)
}
}
#Made an working API. Only need it to work with my website.
10 messages · Page 1 of 1 (latest)
// Data struct from ESPHome
type Data struct {
Name float32 `json:"name"`
Genre float32 `json:"genre"`
}
// handleDataReceivedRequest
func handleDataReceivedRequest(w http.ResponseWriter, r *http.Request) {
// return if request type is not post and send http status 500 (internal
// server error)
if r.Method != "POST" {
_, err := fmt.Fprintln(w, "API only can be called by POST Request")
if err != nil {
fmt.Printf("Writing to http client error: %v\n", err)
}
w.WriteHeader(http.StatusInternalServerError)
return
}
// read full request body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("Reading http request body error: %v\n", err)
return
}
// get data from request body
data := Data{}
err = json.Unmarshal(body, &data)
if err != nil {
fmt.Printf("Unmarshal json from http request body error: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// prepare mysql query
stmt, err := db.Prepare("INSERT INTO " + viper.GetString("dbtable") + " (name,genre) VALUES(?,?);")
if err != nil {
fmt.Printf("Preparing mysql query error: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// execute mysql query
_, err = stmt.Exec(data.Name, data.Genre)
if err != nil {
fmt.Printf("Executing mysql query error: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprintln(w, "Success")
}
and this is my website
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Get and Post request</title>
</head>
<body>
<h1>Simple Get and POST request using fetch API
method by making custom library</h1>
<!-- Including library.js file and app.js file -->
<script src="library.js"></script>
<script src="app.js"></script>
</body>
</html>
// Instantiating EasyHTTP
const http = new EasyHTTP;
// Get prototype method
http.get('http://ip:15000/')
// Resolving promise for response data
.then(data => console.log(data))
// Resolving promise for error
.catch(err => console.log(err));
// Data for post request
const data = {
Name: 'selmon_bhoi',
Genre: '_selmon',
}
// Post prototype method
http.post(
'http://ip:15000/',
data)
// resolving promise for response data
.then(data => console.log(data))
// resolving promise for error
.catch(err => console.log(err));
class EasyHTTP {
// Make an HTTP GET Request
async get(url) {
// Awaiting for fetch response
const response = await fetch(url);
// Awaiting for response.json()
const resData = await response.json();
// Returning result data
return resData;
}
// Make an HTTP POST Request
async post(url, data) {
// Awaiting for fetch response and
// defining method, headers and body
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
// Awaiting response.json()
const resData = await response.json();
// Returning result data
return resData;
}
}
Aight unsure if I understand your question correctly but if you want to restrict your API so it only can be hit from your specific website then you need to do a bit of reading on CORS:
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in ord...
Should look something like this: w.Header().Set("Access-Control-Allow-Origin", "YOURWEBSITEURL")