Skip to content

Instantly share code, notes, and snippets.

@zeyneloz
Last active May 2, 2019 09:20
Show Gist options
  • Save zeyneloz/024aec1422a3bc24c06a0ab0e69a1f8f to your computer and use it in GitHub Desktop.
Save zeyneloz/024aec1422a3bc24c06a0ab0e69a1f8f to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type loginSchema struct {
Username string `json:"username"`
Password string `json:"password"`
}
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, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Body read error, %v", err)
w.WriteHeader(500) // Return 500 Internal Server Error.
return
}
// Parse body as json.
var schema loginSchema
if err = json.Unmarshal(body, &schema); err != nil {
log.Printf("Body parse error, %v", err)
w.WriteHeader(400) // Return 400 Bad Request.
return
}
ok, err := loginUser(schema.Username, schema.Password)
if err != nil {
log.Printf("Login user DB error, %v", err)
w.WriteHeader(500) // Return 500 Internal Server Error.
return
}
if !ok {
log.Printf("Unauthorized access for user: %v", schema.Username)
w.WriteHeader(401) // Wrong password or username, Return 401.
return
}
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