Browse Source

Added proper comments, improved some style

Piotr Czajkowski 7 years ago
parent
commit
f3d9c48223
6 changed files with 35 additions and 14 deletions
  1. 13 8
      app.go
  2. 4 1
      logger.go
  3. 9 2
      search.go
  4. 1 1
      search_test.go
  5. 3 0
      server.go
  6. 5 2
      tm.go

+ 13 - 8
app.go

@@ -12,12 +12,14 @@ import (
 	"time"
 )
 
+// Application stores main information needed to run the app
 type Application struct {
 	Name, AccessToken, Sid, BaseURL, AuthString string
 	Languages                                   map[string]string
 	Delay                                       time.Duration
 }
 
+// SetBaseURL sets base URL for API endpoint.
 func (app *Application) SetBaseURL(url string) {
 	if !strings.HasSuffix(url, "/") {
 		url += "/"
@@ -25,27 +27,29 @@ func (app *Application) SetBaseURL(url string) {
 	app.BaseURL = url
 }
 
-func JsonDecoder(data io.ReadCloser, target interface{}) {
+// JSONDecoder decodes json to given interface, borrowed from SO.
+func JSONDecoder(data io.ReadCloser, target interface{}) {
 	decoder := json.NewDecoder(data)
 
 	err := decoder.Decode(target)
 	if err != nil {
-		log.Printf("error reading json: %v", err)
+		log.Printf("Error reading json: %v", err)
 	}
 }
 
+// LoadLanguages loads languages from languages.json to map.
 func (app *Application) LoadLanguages() {
 	data, err := os.Open("./html/languages.json")
 	defer data.Close()
 	if err != nil {
-		log.Printf("error reading languages: %v", err)
-		return
+		log.Fatalf("Error reading languages: %v", err)
 	}
 
 	app.Languages = make(map[string]string)
-	JsonDecoder(data, &app.Languages)
+	JSONDecoder(data, &app.Languages)
 }
 
+// CheckLanguage checks if language is in the map.
 func (app Application) CheckLanguage(language string) bool {
 	_, ok := app.Languages[language]
 	if !ok {
@@ -55,10 +59,11 @@ func (app Application) CheckLanguage(language string) bool {
 	return true
 }
 
+// Login logs into the API and sets AuthString.
 func (app *Application) Login() {
 	credentials, err := ioutil.ReadFile("./secrets.json")
 	if err != nil {
-		log.Printf("Error reading credentials: %v", err)
+		log.Fatalf("Error reading credentials: %v", err)
 	}
 
 	loginURL := app.BaseURL + "auth/login"
@@ -69,11 +74,11 @@ func (app *Application) Login() {
 	client := &http.Client{}
 	resp, err := client.Do(req)
 	if err != nil {
-		log.Printf("error logging in: %v", err)
+		log.Fatalf("Error logging in: %v", err)
 	}
 	defer resp.Body.Close()
 
-	JsonDecoder(resp.Body, &app)
+	JSONDecoder(resp.Body, &app)
 
 	app.AuthString = "?authToken=" + app.AccessToken
 	log.Println(app.AuthString, resp.Status)

+ 4 - 1
logger.go

@@ -10,6 +10,7 @@ import (
 	"time"
 )
 
+// GetInfoFromRequest reads information from given request and returns them as tuple.
 func GetInfoFromRequest(r *http.Request) (string, string, string) {
 	host, _, _ := net.SplitHostPort(r.RemoteAddr)
 	searchPhrase := r.URL.Query().Get("phrase")
@@ -23,6 +24,7 @@ func GetInfoFromRequest(r *http.Request) (string, string, string) {
 	return host, searchPhrase, language
 }
 
+// WriteLog writes log entry to the file.
 func WriteLog(logString string) error {
 	logFile := filepath.Join("log", (time.Now().Format("200612") + ".log"))
 	logOutput, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
@@ -35,6 +37,7 @@ func WriteLog(logString string) error {
 	return err
 }
 
+// Logger main function, saves event to the log.
 func Logger(r *http.Request, resultsServed int) {
 	host, searchPhrase, language := GetInfoFromRequest(r)
 	timeFormat := "2006-01-02 15:04:05"
@@ -48,6 +51,6 @@ func Logger(r *http.Request, resultsServed int) {
 
 	err := WriteLog(logString)
 	if err != nil {
-		log.Fatalf("error writing log: %v", err)
+		log.Fatalf("Error writing log: %v", err)
 	}
 }

+ 9 - 2
search.go

@@ -8,27 +8,32 @@ import (
 	"time"
 )
 
+// Segment stores source and translated texts.
 type Segment struct {
 	Source, Target string
 }
 
+// Clean cleans <seg> tags from source and translated texts.
 func (s *Segment) Clean() {
 	re := regexp.MustCompile("</?seg>")
 	s.Source = re.ReplaceAllString(s.Source, "")
 	s.Target = re.ReplaceAllString(s.Target, "")
 }
 
+// CleanedResults stores processed results from given TM.
 type CleanedResults struct {
 	TMName   string
 	Segments []Segment
 }
 
+// SearchResults stores processed results from all TMs.
 type SearchResults struct {
 	SearchPhrase string
 	Results      []CleanedResults
 	TotalResults int
 }
 
+// ResultsFromServer stores results as received from server.
 type ResultsFromServer struct {
 	ConcResult []struct {
 		ConcordanceTextRanges []struct {
@@ -44,6 +49,7 @@ type ResultsFromServer struct {
 	TotalConcResult         int
 }
 
+// PostQuery sends POST query to server and returns response.
 func PostQuery(requestURL string, searchJSON []byte) *http.Response {
 	req, err := http.NewRequest("POST", requestURL, bytes.NewBuffer(searchJSON))
 	req.Header.Set("Content-Type", "application/json")
@@ -51,12 +57,13 @@ func PostQuery(requestURL string, searchJSON []byte) *http.Response {
 	client := &http.Client{}
 	resp, err := client.Do(req)
 	if err != nil {
-		log.Printf("error posting query: %v", err)
+		log.Printf("Error posting query: %v", err)
 	}
 
 	return resp
 }
 
+// Search searches for given phrase in given TMs.
 func (app *Application) Search(TMs []TM, text string) SearchResults {
 	searchString := "{ \"SearchExpression\": [ \"" + text + "\" ]}"
 	searchJSON := []byte(searchString)
@@ -81,7 +88,7 @@ func (app *Application) Search(TMs []TM, text string) SearchResults {
 		}
 
 		var tempResults ResultsFromServer
-		JsonDecoder(resp.Body, &tempResults)
+		JSONDecoder(resp.Body, &tempResults)
 
 		if tempResults.TotalConcResult > 0 {
 			var tmResults CleanedResults

+ 1 - 1
search_test.go

@@ -58,7 +58,7 @@ func TestSearch(t *testing.T) {
 	}
 
 	var tms []TM
-	JsonDecoder(tmsJSON, &tms)
+	JSONDecoder(tmsJSON, &tms)
 
 	testSourceSegment1 := "<bpt i='1' type='bold'>{}</bpt>Something Test/ Whatever<ept i='1'>{}</ept>"
 	testSourceSegment2 := "<bpt i='1' type='bold'>{}</bpt>Another Test/ Anything<ept i='1'>{}</ept>"

+ 3 - 0
server.go

@@ -14,6 +14,7 @@ var url = flag.String("b", "", "API URL")
 var app Application
 var errorPage = template.Must(template.ParseFiles("./html/error.html"))
 
+// ServeIndex serves index page.
 func ServeIndex(w http.ResponseWriter, r *http.Request) {
 	t := template.Must(template.ParseFiles("./html/index.html"))
 	t.Execute(w, app.Languages)
@@ -24,6 +25,7 @@ func add(x, y int) int {
 	return x + y
 }
 
+// DisplaySearchResults displays search results as HTML page.
 func DisplaySearchResults(w http.ResponseWriter, r *http.Request) {
 	language := r.URL.Query().Get("lang")
 	searchPhrase := r.URL.Query().Get("phrase")
@@ -50,6 +52,7 @@ func DisplaySearchResults(w http.ResponseWriter, r *http.Request) {
 	}
 }
 
+// DisplayTMs displays TMs as HTML page.
 func DisplayTMs(w http.ResponseWriter, r *http.Request) {
 	language := r.URL.Query().Get("lang")
 

+ 5 - 2
tm.go

@@ -6,20 +6,23 @@ import (
 	"time"
 )
 
+// TM stores information about TM.
 type TM struct {
 	NumEntries, AccessLevel                                                                         int
 	Client, Domain, FriendlyName, Project, SourceLangCode, Subject, TMGuid, TMOwner, TargetLangCode string
 }
 
+// GetQuery sends GET query and returns response.
 func GetQuery(url string) *http.Response {
 	resp, err := http.Get(url)
 	if err != nil {
-		log.Printf("error getting query: %v", err)
+		log.Printf("Error getting query: %v", err)
 	}
 
 	return resp
 }
 
+// GetTMs returns list of TMs for given target language.
 func (app *Application) GetTMs(language string) []TM {
 	tmURL := app.BaseURL + "tms/"
 	var queryURL string
@@ -38,7 +41,7 @@ func (app *Application) GetTMs(language string) []TM {
 	}
 
 	var results []TM
-	JsonDecoder(resp.Body, &results)
+	JSONDecoder(resp.Body, &results)
 
 	return results
 }