Skip to content

Instantly share code, notes, and snippets.

@kimschles
Last active March 15, 2021 16:06
Show Gist options
  • Save kimschles/d2e69ca5d55a3d2a12921547e412276e to your computer and use it in GitHub Desktop.
Save kimschles/d2e69ca5d55a3d2a12921547e412276e to your computer and use it in GitHub Desktop.
go-database-server
package main
import (
"fmt"
"strings"
"net/http"
)
func sayHello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello!\n This webserver lets you store and retrieve data through query parameters at the end of the URL.\n To save data, use the set path, a question mark and then your key value pair separated by an equals sign. For example, http://localhost:4000/set?somekey=somevalue.\n To retrieve data, use the get path, a question mark, the word key, an equals sign and the name of the key. For example, http://localhost:4000/get?key=somekey.")
}
type query struct {
key string
value string
}
var dataStore []query
func setValues(w http.ResponseWriter, r *http.Request) {
var sessionStore query
queryString := r.URL.RawQuery
sessionStore.key = strings.Split(queryString, "=")[0]
sessionStore.value = strings.Split(queryString, "=")[1]
dataStore = append(dataStore, sessionStore)
fmt.Fprintf(w, "key value pair saved!")
}
func getValues(w http.ResponseWriter, r *http.Request) {
queryString := r.URL.RawQuery
searchTerm := strings.Split(queryString, "=")[1]
success := false
for _, query := range dataStore {
if searchTerm == query.key {
success = true
fmt.Fprintf(w, query.value)
}
}
if !success {
fmt.Fprintf(w, "No key value pair found.")
}
}
func main() {
helloHandler := http.HandlerFunc(sayHello)
http.Handle("/", helloHandler)
setValuesHandler := http.HandlerFunc(setValues)
http.Handle("/set", setValuesHandler)
getValuesHandler := http.HandlerFunc(getValues)
http.Handle("/get", getValuesHandler)
http.ListenAndServe(":4000", nil)
}
@kimschles
Copy link
Author

To run the webserver on your machine, download the file and run go run main.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment