Skip to content

Instantly share code, notes, and snippets.

@emirpasic
Created September 13, 2021 08:27
Show Gist options
  • Save emirpasic/8e70092d8930ccaf52d8916d910675d9 to your computer and use it in GitHub Desktop.
Save emirpasic/8e70092d8930ccaf52d8916d910675d9 to your computer and use it in GitHub Desktop.
Sample HTTP Server Golang
package main
import (
"encoding/json"
"net/http"
)
type input struct {
Word string `json:"word"`
Synonym string `json:"synonym"`
}
type output struct {
Word string `json:"word"`
Synonyms []string `json:"synonyms"`
}
func handler(w http.ResponseWriter, r *http.Request) {
setCORS(w)
switch r.Method {
// OPTIONS ...
case "OPTIONS":
// GET localhost:8080/synonyms?word=begin
case "GET":
word := r.URL.Query().Get("word")
// TODO search synonyms by the the "word" query parameter
o, _ := json.Marshal(
&output{
Word: word,
Synonyms: []string{"a", "b", "c"},
},
)
w.Write(o)
// POST localhost:8080/synonyms
case "POST":
d := json.NewDecoder(r.Body)
i := &input{}
err := d.Decode(i)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// TODO insert the input "i" into data structure
// ...
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func setCORS(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func main() {
http.HandleFunc("/synonym", handler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment