Skip to content

Instantly share code, notes, and snippets.

@nkt
Created February 14, 2016 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkt/9a773510d8718d98bc02 to your computer and use it in GitHub Desktop.
Save nkt/9a773510d8718d98bc02 to your computer and use it in GitHub Desktop.
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