Skip to content

Instantly share code, notes, and snippets.

@zeyneloz
Last active May 2, 2019 08:27
Show Gist options
  • Save zeyneloz/3a798af37c56e76d873a5f8b2bd02930 to your computer and use it in GitHub Desktop.
Save zeyneloz/3a798af37c56e76d873a5f8b2bd02930 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type loginSchema struct {
Username string `json:"username"`
Password string `json:"password"`
}
// Return `true`, nil if given user and password exist in database.
func loginUser(username string, password string) (bool, error) {...}
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(405) // Return 405 Method Not Allowed.
return
}
// Read request body.
body, _ := ioutil.ReadAll(r.Body)
// Parse body as json.
var schema loginSchema
json.Unmarshal(body, &schema)
ok, _ := loginUser(schema.Username, schema.Password)
if !ok {
w.WriteHeader(401) // Wrong password or username, Return 401.
} else {
w.WriteHeader(200) // Successfully logged in.
}
}
func main() {
http.HandleFunc("/login/", loginHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment