42 lines
804 B
Go
42 lines
804 B
Go
package blog
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func readJSON(r *http.Request, data interface{}) error {
|
|
decoder := json.NewDecoder(r.Body)
|
|
return decoder.Decode(data)
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, data interface{}) error {
|
|
if d, err := json.Marshal(data); err != nil {
|
|
return err
|
|
} else {
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(d)))
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Write(d)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func tokenFromRequest(r *http.Request) string {
|
|
var token string
|
|
tokencookie, e := r.Cookie("token")
|
|
if e == nil {
|
|
token = tokencookie.Value
|
|
}
|
|
|
|
if token == "" {
|
|
tmp := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
|
if strings.ToLower(tmp[0]) != "bearer" {
|
|
return ""
|
|
}
|
|
token = tmp[1]
|
|
}
|
|
return token
|
|
}
|