Last active
March 15, 2021 16:06
-
-
Save kimschles/d2e69ca5d55a3d2a12921547e412276e to your computer and use it in GitHub Desktop.
go-database-server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run the webserver on your machine, download the file and run
go run main.go