Browse Source

Updated API to use header auth

thisnthat 5 years ago
parent
commit
b301b7d1d6
3 changed files with 42 additions and 9 deletions
  1. 31 0
      http.go
  2. 7 6
      topics.go
  3. 4 3
      users.go

+ 31 - 0
http.go

@@ -0,0 +1,31 @@
+package discourse
+
+import (
+	"bytes"
+	"net/http"
+	"time"
+)
+
+func newGetRequest(config APIConfig, url string) (*http.Request, error) {
+	req, err := http.NewRequest("GET", url, nil)
+	req.Header.Set("Api-Key", config.APIKey)
+	req.Header.Set("Api-Username", config.APIUsername)
+	req.Header.Set("Content-Type", "application/json")
+
+	return req, err
+}
+
+func newPostRequest(config APIConfig, url string, payload []byte) (*http.Request, error) {
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
+	req.Header.Set("Api-Key", config.APIKey)
+	req.Header.Set("Api-Username", config.APIUsername)
+	req.Header.Set("Content-Type", "application/json")
+
+	return req, err
+}
+
+func getClient() *http.Client {
+	client := &http.Client{Timeout: time.Second * 5}
+
+	return client
+}

+ 7 - 6
topics.go

@@ -1,10 +1,8 @@
 package discourse
 
 import (
-	"bytes"
 	"encoding/json"
 	"fmt"
-	"net/http"
 	"strings"
 )
 
@@ -36,11 +34,14 @@ func SendPM(apiConfig APIConfig, recipients []string, title, body string) (int,
 	}
 
 	payload, _ := json.Marshal(newPm)
-	fmt.Println(string(payload))
-	url := fmt.Sprintf("%s/posts.json?api_key=%s&api_username=%s",
-		apiConfig.Endpoint, apiConfig.APIKey, apiConfig.APIUsername)
 
-	response, err := http.Post(url, "application/json", bytes.NewBuffer(payload))
+	url := fmt.Sprintf("%s/posts.json", apiConfig.Endpoint)
+
+	req, _ := newPostRequest(apiConfig, url, payload)
+	client := getClient()
+
+	response, err := client.Do(req)
+
 	if err != nil {
 		return 0, err
 	}

+ 4 - 3
users.go

@@ -3,7 +3,6 @@ package discourse
 import (
 	"encoding/json"
 	"fmt"
-	"net/http"
 	"strings"
 )
 
@@ -28,9 +27,11 @@ type User struct {
 
 // GetUser - Get a discourse user
 func GetUser(config APIConfig, username string) (User, error) {
-	url := fmt.Sprintf("%s/users/%s.json?api_key=%s&api_username=%s", config.Endpoint, username, config.APIKey, config.APIUsername)
+	url := fmt.Sprintf("%s/users/%s.json", config.Endpoint, username)
 
-	response, _ := http.Get(url)
+	req, _ := newGetRequest(config, url)
+	client := getClient()
+	response, _ := client.Do(req)
 
 	var result *UserResponse
 	json.NewDecoder(response.Body).Decode(&result)