-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[draft] HTTP server with connection to database #247
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
package main | ||
|
||
import ( | ||
"database/sql" | ||
"flag" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"os" | ||
_ "github.com/mattn/go-sqlite3" | ||
aslonnie marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"encoding/json" | ||
) | ||
|
||
type MachineConfigInput struct { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. don't need to cap starting with cap means it is "public" There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
Name string `json:"name"` | ||
Configuration string `json:"configuration"` | ||
} | ||
|
||
type MachineConfig struct { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
id int | ||
name string | ||
configuration string | ||
} | ||
|
||
// a function to connect to database given a path to .db file | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
func connectToDatabase(dbPath string) (*sql.DB, error) { | ||
db, err := sql.Open("sqlite3", dbPath) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. removed this func and used |
||
if err != nil { | ||
return nil, err | ||
} | ||
return db, nil | ||
} | ||
|
||
// a function to handle GET request to /machine/configuration that query the machine config based on name | ||
func handleGetRequest(db *sql.DB, w http.ResponseWriter, r *http.Request) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could you define a server struct/class, with db wrapped in it? and make this a method of that server? |
||
// Parse the query parameter | ||
name := r.URL.Query().Get("name") | ||
|
||
var rows *sql.Rows | ||
var err error | ||
// If name is specified, query the machine config with that name | ||
if name != "" { | ||
rows, err = db.Query("SELECT id, name, configuration FROM machine_config WHERE name = ?", name) | ||
} else { | ||
rows, err = db.Query("SELECT id, name, configuration FROM machine_config") | ||
} | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you do not want to return internal sql errors directly to user. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done. I send the sql errors to log instead and only mention internal error |
||
return | ||
} | ||
defer rows.Close() | ||
|
||
// Iterate through the queried rows and print out | ||
var machineConfigs []MachineConfig | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. use in general, use struct pointers for most cases. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
for rows.Next() { | ||
var machineConfig MachineConfig | ||
err := rows.Scan(&machineConfig.id, &machineConfig.name, &machineConfig.configuration) | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
machineConfigs = append(machineConfigs, machineConfig) | ||
} | ||
if err = rows.Err(); err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
for _, machineConfig := range machineConfigs { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. use single char var name for There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
fmt.Fprintf(w, "ID: %d, Name: %s, Configuration: %s\n", machineConfig.id, machineConfig.name, machineConfig.configuration) | ||
} | ||
} | ||
|
||
//a function to handle POST request in MachineConfig format to add a machine configuration to the database | ||
func handlePostRequestMachineConfig(db *sql.DB, w http.ResponseWriter, r *http.Request) { | ||
// Make sure the content type is JSON | ||
if r.Header.Get("Content-Type") != "application/json" { | ||
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType) | ||
return | ||
} | ||
|
||
// Parse the JSON body | ||
config := &MachineConfigInput{} | ||
err := json.NewDecoder(r.Body).Decode(config) | ||
if err != nil { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
this limits the scope of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
http.Error(w, "Invalid JSON format: "+err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// Insert into database | ||
_, err = db.Exec("INSERT INTO machine_config (name, configuration) VALUES (?, ?)", | ||
config.Name, config.Configuration) | ||
if err != nil { | ||
http.Error(w, "Database error: "+err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
} | ||
|
||
func main() { | ||
dbPath := flag.String("db", "reef.db", "Path to .db file") | ||
flag.Parse() | ||
if _, err := os.Stat(*dbPath); os.IsNotExist(err) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you want to handle other types of error too; don't drop error There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
log.Fatalf("File %s does not exist", *dbPath) | ||
} | ||
|
||
db, err := connectToDatabase(*dbPath) | ||
if err != nil { | ||
log.Fatalf("Error connecting to database: %s", err) | ||
} | ||
defer db.Close() | ||
|
||
// handle both GET and POST request to /machine/configuration | ||
http.HandleFunc("/machine/configuration", func(w http.ResponseWriter, r *http.Request) { | ||
switch r.Method { | ||
case http.MethodGet: | ||
handleGetRequest(db, w, r) | ||
case http.MethodPost: | ||
handlePostRequestMachineConfig(db, w, r) | ||
default: | ||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) | ||
} | ||
}) | ||
log.Printf("Starting server") | ||
http.ListenAndServe(":1234", nil) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. handle the err being returned. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you would like to apply
go fmt
to the fileThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done