12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package xhttp
- import (
- "encoding/json"
- "encoding/xml"
- "net/http"
- "net/url"
- "git.chuangxin1.com/myth/sacred"
- )
- // Message HTTP response
- type Message struct {
- req *http.Request
- res *http.Response
- StatusCode int
- Body []byte
- Header http.Header
- }
- // JSON Body to JSON
- func (m Message) JSON(v interface{}) error {
- return json.Unmarshal(m.Body, v)
- }
- // XML Body to XML
- func (m Message) XML(v interface{}) error {
- return xml.Unmarshal(m.Body, v)
- }
- // Cookies parses and returns the cookies set in the Set-Cookie headers.
- func (m Message) Cookies() []*http.Cookie {
- return m.res.Cookies()
- }
- // Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to the Response's Request. ErrNoLocation is returned if no Location header is present.
- func (m Message) Location() (*url.URL, error) {
- return m.res.Location()
- }
- // UserAgent returns the client's User-Agent, if sent in the request.
- func (m Message) UserAgent() string {
- return m.req.UserAgent()
- }
- // Referer returns the referring URL, if sent in the request.
- func (m Message) Referer() string {
- return m.req.Referer()
- }
- func header(w http.ResponseWriter, contentType string) {
- w.Header().Set(`Content-Type`, contentType)
- w.Header().Set(`X-Powered-By`, sacred.LibName+`/`+sacred.LibVersion)
- w.WriteHeader(http.StatusOK)
- }
- // SetHeader set http response header
- func SetHeader(w http.ResponseWriter, key, value string) {
- w.Header().Set(key, value)
- }
- // Redirect redirect
- func Redirect(w http.ResponseWriter, r *http.Request, url string) {
- //w.Header().Set(`Location`, url)
- //w.WriteHeader(http.StatusFound)
- http.Redirect(w, r, url, http.StatusFound)
- }
- // WriteJSON response JSON data.
- func WriteJSON(w http.ResponseWriter, response interface{}) error {
- header(w, `application/json; charset=utf-8`)
- return json.NewEncoder(w).Encode(response)
- }
- // WriteXML response XML data.
- func WriteXML(w http.ResponseWriter, response interface{}) error {
- header(w, `application/xml; charset=utf-8`)
- return xml.NewEncoder(w).Encode(response)
- }
- // WriteBytes response bytes
- func WriteBytes(w http.ResponseWriter, response interface{}) error {
- header(w, `text/html; charset=utf-8`)
- _, err := w.Write(response.([]byte))
- return err
- }
|