Created
May 1, 2019 11:19
-
-
Save hliyan/8b77072c6a6e329305549edcaacf3407 to your computer and use it in GitHub Desktop.
REST API in Go
This file contains 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 ( | |
"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