Created
February 14, 2016 19:32
-
-
Save nkt/9a773510d8718d98bc02 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"log" | |
"net/http" | |
"encoding/json" | |
"golang.org/x/crypto/bcrypt" | |
) | |
type HashRequest struct { | |
Password string `json:"password"` | |
} | |
type HashResponse struct { | |
Result string `json:"result"` | |
} | |
type CompareRequest struct { | |
Hash string `json:"hash"` | |
Password string `json:"password"` | |
} | |
type CompareResponse struct { | |
Result bool `json:"result"` | |
} | |
func main() { | |
http.HandleFunc("/hash", hashHandler) | |
http.HandleFunc("/compare", compareHandler) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
func hashHandler(w http.ResponseWriter, r *http.Request) { | |
if r.Method != "POST" { | |
http.Error(w, r.Method+" not allowed", http.StatusMethodNotAllowed) | |
return | |
} | |
req := HashRequest{} | |
json.NewDecoder(r.Body).Decode(req) | |
result, _ := bcrypt.GenerateFromPassword([]byte(req.Password), 10) | |
res := HashResponse{string(result)} | |
json.NewEncoder(w).Encode(res) | |
} | |
func compareHandler(w http.ResponseWriter, r *http.Request) { | |
if r.Method != "POST" { | |
http.Error(w, r.Method+" not allowed", http.StatusMethodNotAllowed) | |
return | |
} | |
req := CompareRequest{} | |
json.NewDecoder(r.Body).Decode(req) | |
err := bcrypt.CompareHashAndPassword( | |
[]byte(req.Hash), | |
[]byte(req.Password), | |
) | |
res := CompareResponse{err == nil} | |
json.NewEncoder(w).Encode(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment