Last active
June 11, 2018 09:04
-
-
Save proclaim/a2bd4c288d3b349693430839ff4e2c50 to your computer and use it in GitHub Desktop.
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" | |
"github.com/gorilla/mux" | |
"log" | |
"net/http" | |
) | |
type Response struct { | |
Successful bool `json:"successful"` | |
Data interface{} `json:"data"` | |
Err error `json:"error"` | |
} | |
func main() { | |
router := mux.NewRouter() | |
router.HandleFunc("/save/something", handle(saveSomething)) | |
log.Fatal(http.ListenAndServe(":8000", router)) | |
} | |
func saveSomething(w http.ResponseWriter, r *http.Request) (interface{}, int, error) { | |
return "secret token", 200, nil | |
} | |
func handle(f func(http.ResponseWriter, *http.Request) (interface{}, int, error)) func(w http.ResponseWriter, r *http.Request) { | |
return func(w http.ResponseWriter, r *http.Request) { | |
data, status, err := f(w, r) | |
w.Header().Add("Content-Type", "application/json") | |
w.WriteHeader(status) | |
if err != nil { | |
json.NewEncoder(w).Encode(Response{ | |
Successful: false, | |
Data: nil, | |
Err: err, | |
}) | |
return | |
} | |
log.Println(data, status, err) | |
json.NewEncoder(w).Encode(Response{ | |
Successful: true, | |
Data: data, | |
Err: nil, | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment