Created
October 12, 2015 22:11
-
-
Save pietrocaselani/355d0f70808708a0aacf to your computer and use it in GitHub Desktop.
A simple web service in Go
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
// usage: curl -H "Content-Type: application/json" -d '{"N1":3.1, "N2":5.7}' http://localhost:8080 | |
package main | |
import ( | |
"net/http" | |
"encoding/json" | |
"github.com/gorilla/mux" | |
"log" | |
"fmt" | |
) | |
type Result struct { | |
Sum float64 `json:"sum"` | |
Sub float64 `json:"sub"` | |
Mul float64 `json:"mul"` | |
Div float64 `json:"div"` | |
} | |
type Operation struct { | |
N1 float64 | |
N2 float64 | |
} | |
func main() { | |
router := mux.NewRouter().StrictSlash(true) | |
router.HandleFunc("/", Index) | |
log.Fatal(http.ListenAndServe(":8080", router)) | |
} | |
func Index(w http.ResponseWriter, r *http.Request) { | |
decoder := json.NewDecoder(r.Body) | |
var op Operation | |
err := decoder.Decode(&op) | |
if err != nil { | |
w.WriteHeader(http.StatusBadRequest) | |
} else { | |
jsonResult := Result{ | |
Sum:op.N1 + op.N2, | |
Sub:op.N1 - op.N2, | |
Mul:op.N1 * op.N2, | |
Div:op.N1 / op.N2, | |
} | |
err = json.NewEncoder(w).Encode(jsonResult) | |
if (err != nil) { | |
w.WriteHeader(http.StatusInternalServerError) | |
fmt.Fprint(w, err.Error()) | |
} else { | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
w.WriteHeader(http.StatusOK) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment