matrixprotobuf

git clone git://archive.git.mtrnord.blog/MTRNord/matrixprotobuf.git
Log | Files | Refs | README | LICENSE

matrixRequests.go (1452B)


      1 package noAuth
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/json"
      6 	"errors"
      7 	"fmt"
      8 	"github.com/Nordgedanken/MatrixProtoBuf/jsonTypes"
      9 	"io/ioutil"
     10 	"net/http"
     11 )
     12 
     13 func Login(address string, req *jsonTypes.ReqLogin, resp *jsonTypes.RespLogin) (err error, errCode int64) {
     14 	var data []byte
     15 	data, err = json.Marshal(req)
     16 	if err != nil {
     17 		errCode = 500
     18 		return
     19 	}
     20 
     21 	reqresp, err := http.Post("https://"+address+"/_matrix/client/r0/login", "application/json", bytes.NewBuffer(data))
     22 	if err != nil {
     23 		errCode = 500
     24 		return
     25 	}
     26 
     27 	defer reqresp.Body.Close()
     28 	body, err := ioutil.ReadAll(reqresp.Body)
     29 
     30 	if reqresp.StatusCode/100 != 2 { // not 2xx
     31 		var wrap error
     32 		var respErr jsonTypes.RespError
     33 		if _ = json.Unmarshal(body, &respErr); respErr.ErrCode != "" {
     34 			fmt.Errorf(respErr.Error())
     35 			errCode = 3
     36 			err = errors.New("failed to interpret JSON ERROR from Login Endpoint of the defined HS")
     37 			return
     38 		}
     39 
     40 		// If we failed to decode as RespError, don't just drop the HTTP body, include it in the
     41 		// HTTP error instead (e.g proxy errors which return HTML).
     42 		msg := "Failed to POST JSON to " + reqresp.Request.URL.String()
     43 		if wrap == nil {
     44 			msg = msg + ": " + string(body)
     45 		}
     46 
     47 		errCode = int64(reqresp.StatusCode)
     48 		err = errors.New(msg)
     49 		return
     50 	}
     51 
     52 	if err = json.Unmarshal(body, resp); err != nil {
     53 		fmt.Errorf(err.Error())
     54 		errCode = 500
     55 		err = errors.New("failed to interpret JSON from Login Endpoint of the defined HS")
     56 		return
     57 	}
     58 	return
     59 }