Skip to content

Instantly share code, notes, and snippets.

@hliyan
Created May 1, 2019 11:19
Show Gist options
  • Save hliyan/8b77072c6a6e329305549edcaacf3407 to your computer and use it in GitHub Desktop.
Save hliyan/8b77072c6a6e329305549edcaacf3407 to your computer and use it in GitHub Desktop.
REST API in Go
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
type Greeting struct {
Greeting string `json:"greeting"`
Error string `json:"error,omitempty"`
}
who := r.URL.Query().Get("who")
res := Greeting{}
if who == "" {
res.Error = "Greet who?"
} else {
res.Greeting = fmt.Sprintf("Hello %s", who)
}
jsonRes, _ := json.Marshal(res)
io.WriteString(w, string(jsonRes))
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Println(err)
return
}
log.Println("Server exit")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment