當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Context.WriteResponse方法代碼示例

本文整理匯總了Golang中github.com/microcosm-cc/microcosm/models.Context.WriteResponse方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.WriteResponse方法的具體用法?Golang Context.WriteResponse怎麽用?Golang Context.WriteResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/microcosm-cc/microcosm/models.Context的用法示例。


在下文中一共展示了Context.WriteResponse方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Read

// Read handles GET
func (ctl *FileController) Read(c *models.Context) {
	fileHash := c.RouteVars["fileHash"]
	if fileHash == "" {
		c.RespondWithErrorMessage(
			fmt.Sprintf("The supplied file hash cannot be zero characters: %s", c.RouteVars["fileHash"]),
			http.StatusBadRequest,
		)
		return
	}

	fileBytes, headers, _, err := models.GetFile(fileHash)
	if err != nil {
		c.RespondWithErrorMessage(
			fmt.Sprintf("Could not retrieve file: %v", err.Error()),
			http.StatusInternalServerError,
		)
		return
	}

	oneYear := time.Hour * 24 * 365
	nextYear := time.Now().Add(oneYear)
	c.ResponseWriter.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", oneYear/time.Second))
	c.ResponseWriter.Header().Set("Expires", nextYear.Format(time.RFC1123))

	for h, v := range headers {
		c.ResponseWriter.Header().Set(h, v)
	}

	c.WriteResponse(fileBytes, http.StatusOK)
	return
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:32,代碼來源:files.go

示例2: Read

// Read handles GET
func (ctl *GeoCodeController) Read(c *models.Context) {
	c.ResponseWriter.Header().Set("Content-Type", "application/json")

	// Debugging info
	dur := time.Now().Sub(c.StartTime)

	place := strings.Trim(c.Request.URL.Query().Get("q"), " ")

	if strings.Trim(c.Request.URL.Query().Get("q"), " ") == "" {
		ctl.Error(c, "query needed", http.StatusBadRequest)
		return
	}
	if c.Auth.ProfileID <= 0 {
		ctl.Error(c, "no auth", http.StatusForbidden)
		return
	}

	u, _ := url.Parse("http://open.mapquestapi.com/nominatim/v1/search.php")
	q := u.Query()
	q.Set("format", "json")
	// We are not interested in the array returned, just the best match which is the first response
	q.Set("limit", "1")
	q.Set("q", place)
	u.RawQuery = q.Encode()

	resp, err := http.Get(u.String())
	if err != nil {
		ctl.Error(c, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		ctl.Error(c, err.Error(), http.StatusInternalServerError)
		return
	}

	// Again, not interested in the outer array [], so we substring that out
	t := string(body)
	t = t[1 : len(t)-1]

	// But if we now have nothing (no matches were found, we need to return an empty object)
	if strings.Trim(t, ` `) == `` {
		t = `{}`
	}
	body = []byte(t)

	// Return our JavaScript object
	contentLength := len(body)
	c.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(contentLength))
	go models.SendUsage(c, http.StatusOK, contentLength, dur, []string{})

	c.WriteResponse([]byte(body), http.StatusOK)
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:56,代碼來源:geocode.go

示例3: Error

// Error is a generic error handler for the Geo controller
func (ctl *GeoCodeController) Error(c *models.Context, message string, status int) {
	errorJSON := `{"error":["` + message + `"]}`

	contentLength := len(errorJSON)
	c.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(contentLength))

	dur := time.Now().Sub(c.StartTime)
	go models.SendUsage(c, status, contentLength, dur, []string{"message"})

	c.WriteResponse([]byte(errorJSON), status)
	return
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:13,代碼來源:geocode.go

示例4: ReadMany

// ReadMany handles GET
func (ctl *AttendeesCSVController) ReadMany(c *models.Context) {
	eventID, err := strconv.ParseInt(c.RouteVars["event_id"], 10, 64)
	if err != nil {
		c.RespondWithErrorMessage(
			fmt.Sprintf("The supplied event_id ('%s') is not a number.", c.RouteVars["event_id"]),
			http.StatusBadRequest,
		)
		return
	}

	// Start Authorisation
	perms := models.GetPermission(
		models.MakeAuthorisationContext(
			c, 0, h.ItemTypes[h.ItemTypeEvent], eventID),
	)
	if !perms.CanRead {
		c.RespondWithErrorMessage(h.NoAuthMessage, http.StatusForbidden)
		return
	}
	if !(perms.IsOwner || perms.IsModerator || perms.IsSiteOwner) {
		c.RespondWithErrorMessage(h.NoAuthMessage, http.StatusForbidden)
		return
	}
	// End Authorisation

	attendees, status, err := models.GetAttendeesCSV(c.Site.ID, eventID, c.Auth.ProfileID)
	if err != nil {
		c.RespondWithErrorDetail(err, status)
		return
	}

	c.ResponseWriter.Header().Set(`Cache-Control`, `no-cache, max-age=0`)
	c.ResponseWriter.Header().Set(`Vary`, `Authorization`)
	c.ResponseWriter.Header().Set(`Content-Type`, `text/csv`)
	c.ResponseWriter.Header().Set(`Content-Disposition`, fmt.Sprintf(`attachment; filename=event%d.csv`, eventID))
	c.WriteResponse([]byte(attendees), http.StatusOK)
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:38,代碼來源:attendeescsv.go

示例5: Read


//.........這裏部分代碼省略.........

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.Comments,
			metric.Conversations,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Content Creation',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Change in Content Creation
	idPrefix = `ccc_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Comments-Delta', 'Conversations-Delta'],`

	prev := metrics[0]
	for _, metric := range metrics[1:] {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			(metric.Comments - prev.Comments),
			(metric.Conversations - prev.Conversations),
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Content Creation',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Raw Data
	html += `<table>
<tr>
	<th>Timestamp</th>
	<th>Total forums</th>
	<th>Engaged forums</th>
	<th>Conversations</th>
	<th>Comments</th>
	<th>Total profiles</th>
	<th>Edited profiles</th>
	<th>New profiles</th>
	<th>Siginins</th>
	<th>Uniques</th>
	<th>Visits</th>
	<th>Pageviews</th>
</tr>
`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>
`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.TotalForums,
			metric.EngagedForums,
			metric.Conversations,
			metric.Comments,
			metric.TotalProfiles,
			metric.EditedProfiles,
			metric.NewProfiles,
			metric.Signins,
			metric.Uniques,
			metric.Visits,
			metric.Pageviews,
		)
	}
	html += `</table>`

	c.ResponseWriter.Header().Set("Content-Encoding", "text/html")
	c.WriteResponse([]byte(html), http.StatusOK)
	return
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:101,代碼來源:metrics.go


注:本文中的github.com/microcosm-cc/microcosm/models.Context.WriteResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。